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.
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.
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.
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.
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.
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With