Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle newlines in JSON?

I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have:

var data = '{"count" : 1, "stack" : "sometext\n\n"}'; var dataObj = eval('('+data+')'); 

This gives me an error:

unterminated string literal 

With JSON.parse(data), I see similar error messages: "Unexpected token ↵" in Chrome, and "unterminated string literal" in Firefox and IE.

When I take out the \n after sometext the error goes away in both cases. I can't seem to figure out why the \n makes eval and JSON.parse fail.

like image 836
polarbear Avatar asked Sep 03 '08 16:09

polarbear


People also ask

Can you have newlines in JSON?

JSON strings do not allow real newlines in its data; it can only have escaped newlines. Snowflake allows escaping the newline character by the use of an additional backslash character.

Do line breaks matter in JSON?

JSON Simple Array Examples Whitespace (Space, Horizontal tab, Line feed or New line or Carriage return) does not matter in JSON. It can also be minified with no affect to the data.

Do I need to escape ampersand in JSON?

I thought that the escaping would be done inside the library but now I see that the serialization is left untouched the ampersand & character. Yes, for a JSON format this is valid.


2 Answers

This is what you want:

var data = '{"count" : 1, "stack" : "sometext\\n\\n"}'; 

You need to escape the \ in your string (turning it into a double-\), otherwise it will become a newline in the JSON source, not the JSON data.

like image 97
BlaM Avatar answered Sep 23 '22 17:09

BlaM


You will need to have a function which replaces \n to \\n in case data is not a string literal.

function jsonEscape(str)  {     return str.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r").replace(/\t/g, "\\\\t"); }  var data = '{"count" : 1, "stack" : "sometext\n\n"}'; var dataObj = JSON.parse(jsonEscape(data)); 

Resulting dataObj will be

Object {count: 1, stack: "sometext\n\n"} 
like image 35
manish_s Avatar answered Sep 23 '22 17:09

manish_s