简体   繁体   English

无法使用JSON.parse解析字符串

[英]Can't parse string with JSON.parse

I have the following code that splits a string on the newline character and then calls JSON.parse on each line. 我有以下代码,该代码在换行符上拆分一个字符串,然后在每一行上调用JSON.parse

var lines = [];
var ks = data.split("\n");
_(ks).each(function(line){
    lines.push(JSON.parse(line));
}, this);
return lines;

The problem is after the split each line is like this 问题是分割后的每一行都是这样

"{"id":"123","attr1":"abc"}"

However in order for JSON.parse to work my string needs to be surrounded my single quotes like 但是为了使JSON.parse工作,我的字符串需要用单引号引起来,例如

'{"id":"123","attr1":"abc"}'

Is there a way to perform this conversion on each line? 有没有一种方法可以在每一行上执行此转换?

If the string is structured like this... 如果字符串的结构是这样的...

"{"id":"123","attr1":"abc"}
{"id":"123","attr1":"abc"}
{"id":"123","attr1":"abc"}
{"id":"123","attr1":"abc"}"

... then a quicker alternative to parsing each line as a separate JSON might be to do this: ...那么将每一行解析为一个单独的JSON的一种更快的替代方法可能是:

JSON.parse("["+data.replace(/^\n+|\n+$/g, "").replace(/\n+/g, ",")+"]");

Doing this replaces each sequence of newlines with a comma, and wraps the resulting line in an array literal, so you have a fresh new array to iterate through. 这样做用逗号替换了换行符的每个序列,并将结果行包装在数组文字中,因此您可以遍历新的新数组。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM