私はここ<pre>
要素内でJSON文字列を読み込むしようとしている:Node.jsでこのJSONを解析するにはどうすればよいですか?
http://nlp.stanford.edu:8080/corenlp/process?input=hello%20world&outputFormat=json
私はマウスで文字列を、コピー&ペーストした場合、私はそれをJSON.parse()
することができます。しかし、プログラムでそれを読んだ場合、エラーが発生します。
var request = require('request'); // to make POST requests
var Entities = require('html-entities').AllHtmlEntities; // to decode the json string (i.e. get rid of nbsp and quot's)
var fs = require('fs')
// Set the headers
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
}
// Configure the request
var options = {
url: 'http://nlp.stanford.edu:8080/corenlp/process',
method: 'POST',
headers: headers,
form: {
'input': 'hello world',
'outputFormat': 'json'
}
}
// Start the request
request(options, function(error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log("body: " + body)
let cheerio = require('cheerio')
let $ = cheerio.load(body)
var inside = $('pre').text();
inside = Entities.decode(inside.toString());
//console.log("inside "+ inside);
var obj = JSON.parse(inside);
console.log(obj);
}
})
しかし、私は次のエラーを取得する:ここで
は私のコードがある
undefined:2
"sentences": [
^
SyntaxError: Unexpected token in JSON at position 2
at JSON.parse (<anonymous>)
そして、ここでは、リンクの出力からの抜粋です、つまり私はobj
に解析したいのか:
{
"sentences": [
{
"index": "0",
...
}
]
}
どのようにすればJSON.parse()
このような文字列ですか?
おかげで、
@ JaredSmithありがとう、私はすでにそれを試みました、それは私のコードに含まれています。しかし、私はまだそれを正しく解析していません。 – jeff
デコードされた文字列はどのように見えますか? 'JSON.parse'は空白を気にするべきではありません... –
私はコンソールに印刷すると普通の文字列のように見えます。しかし、当初、 '{'の前のスペースは予期しないトークンと診断されます。 – jeff