6

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);
Stan
  • 25,744
  • 53
  • 164
  • 242

1 Answers1

13

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}]"};
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335