简体   繁体   中英

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:

<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 + "&deg;");
            $("#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.

Remove the line var json = JSON.parse(response); and your code should work.

According to the jQuery docs on $.ajax (which is what $.get uses internally):

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 ...)

Thus, your response is likely already an object. When you do JSON.parse(response) , you're really doing

JSON.parse("[object Object]")

because JSON.parse coerces its argument to a string , and plain objects by default stringify to [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.

Remove the JSON.parse line, because response is already parsed into an object by jQuery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM