Node.js JSON.parse“Unexpected token {”

时间:2015-08-12 23:03:53

标签: javascript json node.js

我有一个脚本使用JSON.parse(datastring);来解析字符串化的JSON。

datastrings看起来像这样:

{"_id":"8b8fdd243f734b27829c92e4099f70ec.d","date":1439418654920,"player":"player1","action":"capture"}
{"_id":"a3b7d70d8a074f9ba8b13368ee947f1e.d","date":1439418074476,"player":"player1","action":"capture"}

第一个工作正常,但是第二个工作得到了一个奇怪的错误,我无法找到解决方法。

undefined:2
{"_id":"a3b7d70d8a074f9ba8b13368ee947f1e.d","date": 1439418074476,"player":"pla
^
SyntaxError: Unexpected token {
    at Object.parse (native)
    at Socket.<anonymous> (/home/ubuntu/workspace/lib/engine.js:12:18)
    at Socket.emit (events.js:95:17)
    at Socket.<anonymous> (_stream_readable.js:765:14)
    at Socket.emit (events.js:92:17)
    at emitReadable_ (_stream_readable.js:427:10)
    at emitReadable (_stream_readable.js:423:5)
    at readableAddChunk (_stream_readable.js:166:9)
    at Socket.Readable.push (_stream_readable.js:128:10)
    at Pipe.onread (net.js:529:21)

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

JSON.parse期望传递包含JSON文本的字符串,而不是包含多个 JSON文本的字符串。

要么分别解析每一行(假设你可以信任换行符只能在输入中的JSON文本之间)......

var json_texts = datastring.split("\n");

...或者以数组开头表示数据。

[
    {"_id":"8b8fdd243f734b27829c92e4099f70ec.d","date":1439418654920,"player":"player1","action":"capture"},
    {"_id":"a3b7d70d8a074f9ba8b13368ee947f1e.d","date":1439418074476,"player":"player1","action":"capture"}
]