Pattle
Pattle

Reputation: 6016

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.

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

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

Is there a way to perform this conversion on each line?

Upvotes: 0

Views: 2562

Answers (1)

user458541
user458541

Reputation:

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.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. :)

Upvotes: 4

Related Questions