JSON.parse error

<!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 in the second expression of the variable. What for? (Chrome says “unexpected ILLEGAL token”, Firefox says “JSON.parse”)

+4
source share
2 answers

You should use double, not single quotes:

  var str = '{ "foo": "bar" }'; var json = JSON.parse(str); json['foo'] 
+16
source

It was easier for me to just use String () on an object before calling JSON.parse ()

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

All Articles