2014-10-20 40 views
0

我的Node.js应用程序读取的字符串,含有JSON数据,使用GET方法一个Python后端。有时,当我使用JSON.parse(),并刷新页面它成功之后,它提供了一个Unexpected token ,错误。解析JSON在node.js中提供了一个错误

[ 
     { 
     "postid":"c4jgud85mhs658sg4hn94jmd75s67w8r", 
     "email":"[email protected]", 
     "post":"hello world", 
     "comment":[] 
     }, 
     { 
     "postid":"c4jgud85mhs658sg4hn94jmd75s67w8r", 
     "email":"[email protected]", 
     "post":"hello world", 
     "comment":[] 
     } 
] 

通过console.log吉宁JSON对象,我能够验证它只打印对象部分(意味着只有对象的一部分被传递),当它提供错误 - 例如:

4hn94jmd75s67w8r", 
     "email":"[email protected]", 
     "post":"hello world", 
     "comment":[] 
     } 
] 

[ 
     { 
     "postid":"c4jgud85mhs658sg 

在node.js的,林只使用

var data = JSON.parse(resJSON); //resJSON is the variable containing the JSON

+0

这可能是因为JSON是无效的:http://jsonlint.com – Whymarrh 2014-10-20 01:00:53

+0

我检查了我的JSON文件中的browser..its有效 – user3015541 2014-10-20 01:02:49

+0

你缺少一个双引号在'结束评论“在第一个对象。 – mscdex 2014-10-20 01:04:34

回答

3

如果它成功“有时,”我怀疑你解析响应为'data'到达,如:

http.get('...', function (res) { 
    res.on('data', function (data) { 
     console.log(JSON.parse(data.toString())); 
    }); 
}); 

如果响应立即给所有这将工作。但是,它也可以分成多个块,通过多个'data'事件接收。

要处理分块响应,您需要将chunk s和parse作为一个整体进行合并,一旦数据流达到'end'

http.get('...', function (res) { 
    var body = ''; 

    res.on('data', function (chunk) { 
     body += chunk.toString(); 
    }); 

    res.on('end', function() { 
     console.log(JSON.parse(body)); 
    }); 
});