简体   繁体   中英

JSON.parse throws 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 on the second variable statement. Why? (Chrome says "unexpected token ILLEGAL", Firefox says "JSON.parse")

You'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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM