35

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"
3
  • console.log(response); ? Commented Dec 18, 2013 at 14:11
  • 2
    you don't need to parse Commented Dec 18, 2013 at 14:11
  • You already have an object, no need to parse it. Commented May 12, 2018 at 16:06

2 Answers 2

76

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Than make a check if it is an object or use $.ajax and tell it what it is supposed to be....
13

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.