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);
4
  • You have JSON inside your JSON ? Commented Mar 5, 2014 at 14:30
  • 1
    I think you need to to double escape your escape marks. So \\"name\\" instead of \"name\". Commented Mar 5, 2014 at 14:30
  • 2
    Andy is right here. But you should really review how you generate the JSON, there's no reason to pass an array as a JSON string inside the JSON. Commented Mar 5, 2014 at 14:31
  • 2
    @dystroy it's not my code, I just need to fix it. :( Commented Mar 5, 2014 at 14:32

1 Answer 1

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}]"};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.