5
<!DOCTYPE html>

<html>
<head>
    <title></title>
</head>
<body>
    <script>        
        var str = "{ 'foo': 'bar' }";
        var json = JSON.parse(str);
    </script>   
</body>
</html>

This code throws an error on the second variable statement. Why? (Chrome says "unexpected token ILLEGAL", Firefox says "JSON.parse")

4
  • Have a look at the JSON specification :) Commented Nov 13, 2010 at 18:29
  • @Felix Dude, that spec is to long. I don't have time for this. :p Commented Nov 13, 2010 at 18:37
  • Vidas: It's images :-P ;) I just wanted to show, how a string is defined in JSON. Commented Nov 13, 2010 at 18:43
  • @Felix It's possibly the shortest web-standard ever :) Commented Nov 13, 2010 at 19:10

2 Answers 2

16

You're supposed to use double, not single quotes:

 var str = '{ "foo": "bar" }';
 var json = JSON.parse(str); 
 json['foo']
Sign up to request clarification or add additional context in comments.

Comments

0

For me it was easier to just use String() on the object before calling JSON.parse()

var retrievedObject = localStorage.foo;
var encoded = JSON.parse(String(retrievedObject));

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.