0

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?

3
  • that shouldn't be a problem. Show the data as is Commented Jan 16, 2015 at 13:13
  • 4
    You seem to be conflating three different things. String literal syntax is not the same as what the JavaScript console will display when logging strings which is, again, not the same as the data stored within the string. If the data really started with ' and ' then JSON.parse would fail because ' isn't a string delimiter in JSON. Commented Jan 16, 2015 at 13:14
  • 1
    ...and even disregarding the confusion over quotes, if you split a string by newlines characters then you will break JSON. Commented Jan 16, 2015 at 13:21

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Awesome, this solved my problem. Although I did have to just make one change to remove the last comma of the end of the string
Ah right, yeah, sorry... probably should've stripped leading/trailing whitespace first. xD My bad. I'll edit my answer, haha.
Saved my day, bro!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.