本文共 2153 字,大约阅读时间需要 7 分钟。
本文翻译自:
This question already has an answer here: 这个问题已经在这里有了答案:
I am having a problem parsing simple JSON strings. 我在解析简单的JSON字符串时遇到问题。 I have checked them on and it shows that they are valid. 我已经在上检查了它们,并显示它们是有效的。 But when I try to parse them using either JSON.parse
or the jQuery alternative it gives me the error unexpected token o
: 但是,当我尝试使用JSON.parse
或jQuery替代方法解析它们时,它给了我错误的unexpected token o
:
Note: I'm encoding my strings using json_encode()
in PHP. 注意:我在PHP中使用json_encode()
对字符串进行编码。
参考:
cur_ques_details
已经是一个JS对象,您无需解析它
Your data is already an object. 您的数据已经是一个对象。 No need to parse it. 无需解析。 The javascript interpreter has already parsed it for you. javascript解释器已经为您解析了它。
var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};document.write(cur_ques_details['ques_title']);
The source of your error, however, is that you need to place the full JSON string in quotes. 但是,错误的根源是您需要将完整的JSON字符串放在引号中。 The following will fix your sample: 以下将修复您的示例:
As the other respondents have mentioned, the object is already parsed into a JS object so you don't need to parse it. 正如其他受访者所提到的,该对象已经被解析为JS对象,因此您无需解析它。 To demonstrate how to accomplish the same thing without parsing, you can do the following: 为了演示如何在不解析的情况下完成同一件事,您可以执行以下操作:
Response is already parsed, you don't need to parse it again. 响应已经解析,您无需再次解析。 if you parse it again it will give you " unexpected token o
". 如果您再次解析它,它将为您提供“ unexpected token o
”。 if you need to get it as string, you could use JSON.stringify()
如果需要以字符串形式获取它,则可以使用JSON.stringify()
I had the same problem when I submitted data using jQuery AJAX: 使用jQuery AJAX提交数据时,我遇到了同样的问题:
$.ajax({ url:... success:function(data){ //server response's data is JSON //I use jQuery's parseJSON method $.parseJSON(data);//it's ERROR }});
If the response is JSON, and you use this method, the data you get is a JavaScript object, but if you use dataType:"text"
, data is a JSON string. 如果响应为JSON,并且您使用此方法,则获取的数据为JavaScript对象,但如果使用dataType:"text"
,则数据为JSON字符串。 Then the use of $.parseJSON
is okay. 这样就可以使用$.parseJSON
。
转载地址:http://ifexb.baihongyu.com/