<!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")
<!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")
Share Improve this question edited Dec 25, 2011 at 12:38 Šime Vidas asked Nov 13, 2010 at 16:59 Šime VidasŠime Vidas 186k65 gold badges286 silver badges391 bronze badges 4- Have a look at the JSON specification :) – Felix Kling Commented Nov 13, 2010 at 18:29
- @Felix Dude, that spec is to long. I don't have time for this. :p – Šime Vidas Commented Nov 13, 2010 at 18:37
- Vidas: It's images :-P ;) I just wanted to show, how a string is defined in JSON. – Felix Kling Commented Nov 13, 2010 at 18:43
- @Felix It's possibly the shortest web-standard ever :) – Šime Vidas Commented Nov 13, 2010 at 19:10
2 Answers
Reset to default 16You're supposed to use double, not single quotes:
var str = '{ "foo": "bar" }';
var json = JSON.parse(str);
json['foo']
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));