如何用Node.js解析这个JSON?

时间:2017-01-13 17:05:31

标签: javascript json

我正在尝试读取<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的内容:

{
&nbsp;&nbsp;&quot;sentences&quot;: [
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;index&quot;: &quot;0&quot;,
...
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;]
}

我怎样JSON.parse()这样的字符串?

谢谢,

2 个答案:

答案 0 :(得分:2)

最终答案

您提出的输出和错误都指向一个问题,即在打开JSON括号后立即解析空格字符。 我建议你删除所有不在引号内的空格。

如下:

var obj = JSON.parse(str.replace(/(\s+?(?={))|(^\s+)|(\r|\n)|((?=[\[:,])\s+)/gm,''));

原始答案

我建议你删除所有空格。

因此,var obj = JSON.parse(inside.replace(/\s/g,''));应该有效

这是JSFiddle example

修改

更好:var obj = JSON.parse(str.replace(/(\s+?(?={))|(^\s+)|(\r|\n)|((?=[\[:,])\s+)/gm,''));会在引号内留下空格,因为“parse”的值中包含空格

答案 1 :(得分:2)

问题在于所有这些&nbsp;。这些代表了一个不间断的空格字符U+00A0。不幸的是,JSON.parse(正确地)扼杀了这些字符,因为JSON规范RFC 4627仅将常规空格(U+0020),制表符和换行符视为空格。

你可以做hacky事,即用U+00A0替换每个U+0020,但这也会影响字符串内部的不间断空格,这是不理想的。

处理这样的输入数据的最佳方法是使用更容忍其他类型的空白字符的JSON解析库。

为什么你running your own copy of CoreNLP?我想他们不想让你刮他们的服务器。