首页 文章

解析JSON给出“意外令牌o”错误[重复]

提问于
浏览
332

这个问题在这里已有答案:

我在解析简单的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 回答

  • 4

    当我使用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 就可以了 .

  • 1

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

  • 5

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

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

    尝试解析所以:

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

    cur_ques_details 已经是JS对象,您不需要解析它

  • 9

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

  • 9

    使用 JSON.stringify(data);

    $.ajax({
        url: ...
        success:function(data){
            JSON.stringify(data); //to string
            alert(data.you_value); //to view you pop up
        }
    });
    
  • 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>
    

相关问题