SyntaxError: JSON Parse error: Unexpected identifier “object” (anonymous function)

后端 未结 2 1047
野性不改
野性不改 2020-12-11 14:35

I do not understand what went wrong when parsing file:

{ \"t\": -9.30, \"p\": 728.11, \"h\": 87.10 }

javascript code:



        
相关标签:
2条回答
  • 2020-12-11 15:18

    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.

    0 讨论(0)
  • 2020-12-11 15:26

    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.

    0 讨论(0)
提交回复
热议问题