[英]SyntaxError: JSON Parse error: Unexpected identifier “object” (anonymous function)
I do not understand what went wrong when parsing file: 我不了解解析文件时出了什么问题:
{ "t": -9.30, "p": 728.11, "h": 87.10 }
javascript code: JavaScript代码:
<script type="text/javascript">
function check() {
$.get("http://....file.json", function(response, status, xhr) {
if (status == "success") {
var json = JSON.parse(response);
$("#temp").html(json.t + "°");
$("#pressure").html(json.p + " mm hg");
}
if (status == "error") {
$("#temp").html("error");
}
});
}
I receive error: 我收到错误消息:
SyntaxError: JSON Parse error: Unexpected identifier "object"
Most probably your response
is already a JavaScript object and it not required to be parsed. 您的
response
很可能已经是一个JavaScript对象,因此不需要进行解析。
Remove the line var json = JSON.parse(response);
删除行
var json = JSON.parse(response);
and your code should work. 并且您的代码应该可以正常工作。
According to the jQuery docs on $.ajax
(which is what $.get
uses internally): 根据
$.ajax
上的jQuery文档( $.get
内部使用的内容):
dataType: ...If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object ...)
dataType: ...如果未指定,则jQuery将尝试根据响应的MIME类型来推断它(XML MIME类型将产生XML,在1.4 JSON中将产生JavaScript对象 ...)
Thus, your response is likely already an object. 因此,您的回应可能已经是一个对象。 When you do
JSON.parse(response)
, you're really doing 当您执行
JSON.parse(response)
,您实际上是在做
JSON.parse("[object Object]")
because JSON.parse
coerces its argument to a string , and plain objects by default stringify to [object Object]
. 因为
JSON.parse
其参数强制转换为字符串 ,并且默认情况下,普通对象将字符串化为[object Object]
。 The initial [
leads JSON.parse
to expect an array, but it then chokes on the object
token, which does not fit the JSON grammar. 初始
[
导致JSON.parse
期望有一个数组,但随后它阻塞了不适合JSON语法的object
令牌。
Remove the JSON.parse
line, because response
is already parsed into an object by jQuery. 删除
JSON.parse
行,因为jQuery已经将response
解析为对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.