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.
You might want to look into this C# function to escape the string:
http://www.aspcode.net/C-encode-a-string-for-JSON-JavaScript.aspx
I encountered that problem while making a class in PHP4 to emulate json_encode (available in PHP5). Here's what i came up with :
I followed the rules mentionned here. I only used what i needed but i figure that you can adapt it to your needs in the language your are using. The problem in my case wasn't about newlines as i originally thought but about the / not being escaped. I hope this prevent someone else from the little headache i had figuring out what i did wrong.
According to spec: http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf
So you can't pass
0x0A
or0x0C
codes directly. It is forbidden! Spec suggests to use escape sequences for some well defined codes fromU+0000
toU+001F
:As most of programming languages uses
\
for quoting you should escape escape syntax (double-escape - once for language/platform, once for Json itself):I guess this is what you want:
(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.)
Hi i used this function to strip newline or other chars in data to parse JSON data:
You could just escape your string in the server when writing the value of the json field and unescape it when retrieving the value in the client browser, for instance.
The javascript implementation of all major browser have the unescape command.
Example: in the server:
in the browser: