[英]How to parse this JSON with Node.js?
我正在嘗試在此處讀取<pre>
元素內的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()
這樣的字符串?
謝謝,
最終答案
您顯示的輸出和錯誤都指出了在打開JSON括號后立即解析空格字符的問題。 我建議您刪除所有不在引號內的空格。
如下:
var obj = JSON.parse(str.replace(/(\\s+?(?={))|(^\\s+)|(\\r|\\n)|((?=[\\[:,])\\s+)/gm,''));
原始答案
我建議您刪除所有空格。
因此, var obj = JSON.parse(inside.replace(/\\s/g,''));
應該管用
這是一個JSFiddle示例
編輯
更好: var obj = JSON.parse(str.replace(/(\\s+?(?={))|(^\\s+)|(\\r|\\n)|((?=[\\[:,])\\s+)/gm,''));
將在引號內保留空格,因為“ parse”的值中包含空格
問題是所有這些
s。 這些代表不間斷的空格字符U+00A0
。 不幸的是, JSON.parse
(正確地)使這些字符阻塞,因為JSON規范RFC 4627僅將常規空格( U+0020
),制表符和換行符視為空白。
您可以這樣做,可以用U+0020
替換每個U+00A0
,但是這也會影響字符串內部的不間斷空格,這是不理想的。
處理此類輸入數據的最佳方法是使用JSON解析庫,該庫更能容忍其他種類的空白字符。
您為什么不運行自己的CoreNLP副本 ? 我想他們不希望您抓取服務器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.