最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JSON.parse throws error - Stack Overflow

programmeradmin0浏览0评论
<!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
Add a comment  | 

2 Answers 2

Reset to default 16

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));
发布评论

评论列表(0)

  1. 暂无评论