Reputation: 186103
<!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")
Upvotes: 5
Views: 10021
Reputation: 2668
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));
Upvotes: 0
Reputation: 186762
You're supposed to use double, not single quotes:
var str = '{ "foo": "bar" }';
var json = JSON.parse(str);
json['foo']
Upvotes: 16