解析JSON给出“意外令牌o”错误

时间:2013-03-25 14:16:03

标签: javascript json

我在解析简单的JSON字符串时遇到问题。我已在JSONLint上检查了它们,并显示它们有效。但是当我尝试使用JSON.parse或jQuery替代方法解析它们时,它会给我错误unexpected token o

<!doctype HTML>
<html>
  <head>
  </head>
  <body>
    <script type="text/javascript">
      var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
      var ques_list = JSON.parse(cur_ques_details);

      document.write(ques_list['ques_title']);
    </script>
  </body>
</html>

注意:我在PHP中使用json_encode()编码我的字符串。

8 个答案:

答案 0 :(得分:706)

您的数据已经是一个对象。无需解析它。 javascript解释器已经为你解析了它。

var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
document.write(cur_ques_details['ques_title']);

答案 1 :(得分:65)

尝试解析:

var yourval = jQuery.parseJSON(JSON.stringify(data));

答案 2 :(得分:13)

使用JSON.stringify(data);

$.ajax({
    url: ...
    success:function(data){
        JSON.stringify(data); //to string
        alert(data.you_value); //to view you pop up
    }
});

答案 3 :(得分:10)

cur_ques_details已经是一个JS对象,你不需要解析它

答案 4 :(得分:10)

但是,错误的来源是您需要将完整的JSON字符串放在引号中。以下将修复您的样本:

<!doctype HTML>
<html>
    <head>
    </head>
    <body>
        <script type="text/javascript">
            var cur_ques_details ='{"ques_id":"15","ques_title":"jlkjlkjlkjljl"}';
            var ques_list = JSON.parse(cur_ques_details);
            document.write(ques_list['ques_title']);
        </script>
    </body>
</html>

正如其他受访者所提到的,该对象已经被解析为JS对象,因此您无需解析它。要演示如何在不解析的情况下完成相同的操作,您可以执行以下操作:

<!doctype HTML>
<html>
<head>
</head>
    <body>
        <script type="text/javascript">
            var cur_ques_details ={"ques_id":"15","ques_title":"jlkjlkjlkjljl"};
            document.write(cur_ques_details.ques_title);
        </script>
    </body>
</html>

答案 5 :(得分:6)

已经解析了响应,您无需再次解析它。如果你再次解析它会给你“unexpected token o”。如果你需要将它作为字符串,你可以使用JSON.stringify()

答案 6 :(得分:5)

当我使用jQuery AJAX提交数据时遇到了同样的问题:

$.ajax({
   url:...
   success:function(data){
      //server response's data is JSON
      //I use jQuery's parseJSON method 
      $.parseJSON(data);//it's ERROR
   }
});

如果响应是JSON,并且您使用此方法,则获得的数据是JavaScript对象,但如果使用dataType:"text",则数据是JSON字符串。然后使用$.parseJSON就可以了。

答案 7 :(得分:1)

我看到此unexpected token o错误,因为我的(不完整)代码先前已运行(实时重新加载!)并将特定的键控本地存储值设置为[object Object]而不是{}。直到我改变了密钥,事情才开始按预期工作。或者,您可以关注these instructions to delete the incorrectly set localStorage value

相关问题