Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Lint says it's valid but JSON.parse throws error

I have simple JSON that I need to parse to object. Strangely it doesn't work even though if I copy and paste my JSON string to JSONLint (http://jsonlint.com/) it will show that it's valid.

var string = '{"token":"9eebcdc435686459c0e0faac854997f3","email":"201403050007950","id":"13","updated_at":"2014-03-05 10:34:51","messageguides":"[{\"name\":\"Un-named Messaging Guide 1\",\"pages\":[\"sustainabilitydirectors\",\"marketingnbusinessdevelopmentdirectors\"],\"date\":1394015692958}]"}';

var obj = JSON.parse(string); // Unexpected token n

console.log(obj);
like image 976
Stan Avatar asked Mar 05 '14 14:03

Stan


1 Answers

The \ characters in the data are treated as JSON escape characters when you parse the raw JSON.

When you embed that JSON inside a JavaScript string, they are treated as JavaScript escape characters and not JSON escape characters.

You need to escape them as \\ when you express your JSON as a JavaScript string.


That said, you are usually better off just dropping the JSON in to the JavaScript as an object (or array) literal instead of embedding it in a string and then parsing it as a separate step.

var obj = {"token":"9eebcdc435686459c0e0faac854997f3","email":"201403050007950","id":"13","updated_at":"2014-03-05 10:34:51","messageguides":"[{\"name\":\"Un-named Messaging Guide 1\",\"pages\":[\"sustainabilitydirectors\",\"marketingnbusinessdevelopmentdirectors\"],\"date\":1394015692958}]"};
like image 72
Quentin Avatar answered Oct 28 '22 02:10

Quentin