javascript 解析 JSON 返回意外的标识符错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20370387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:19:54  来源:igfitidea点击:

Parse JSON returns unexpected identifier error

javascriptjqueryjsonzepto

提问by RyanP13

I am trying to parse the following JSON string that is being returned to me but am getting an unexpected identifier error in the console.

我正在尝试解析以下返回给我的 JSON 字符串,但在控制台中出现意外的标识符错误。

"{"title":"MyApp Companion","push_hash":"ff06b5b775e45409f9ab470b64d672d0","t":"mr","alert":"Ryjjgv","n":"Foo Bar","action":"open the app at specific location","pid":"7V8meRCJaj","badge":"Increment"}" 

I am using zepto but the method $.parseJSON() throws the error.

我正在使用 zepto 但方法 $.parseJSON() 抛出错误。

回答by Kush

You might have to escape quotes in your string as your string looks like this:

您可能需要对字符串中的引号进行转义,因为您的字符串如下所示:

"your string("your string")"

It should be something like:

它应该是这样的:

"your string(\"your string\")" 

or 'your string("your string")'

或'你的字符串(“你的字符串”)'

or: Remove your first and last quotes

或:删除您的第一个和最后一个引号

Hope this helps.

希望这可以帮助。

回答by Sarath

remove your first and last "or replace with '

删除您的第一个和最后一个"或替换为'

"{
    "title": "MyApp Companion",
    "push_hash": "ff06b5b775e45409f9ab470b64d672d0",
    "t": "mr",
    "alert": "Ryjjgv",
    "n": "Foo Bar",
    "action": "open the app at specific location",
    "pid": "7V8meRCJaj",
    "badge": "Increment"
}"

to

 '{
        "title": "MyApp Companion",
        "push_hash": "ff06b5b775e45409f9ab470b64d672d0",
        "t": "mr",
        "alert": "Ryjjgv",
        "n": "Foo Bar",
        "action": "open the app at specific location",
        "pid": "7V8meRCJaj",
        "badge": "Increment"
    }'

and there is on online TOOL jsonlint.com, to validate your JSON

并且有在线工具 jsonlint.com,以验证您的 JSON

回答by p.s.w.g

Because you're using "to delimit the string literal, the console is parsing the "inside the string as a string delimiter. Try using 'as to delimit the literal:

因为您"用于分隔字符串文字,所以控制台"将字符串内部解析为字符串分隔符。尝试使用'as 来分隔文字:

'{"title":"MyApp Companion", ... }'

Alternatively, you can escape all the "inside the string with \:

或者,您可以使用以下命令转义"字符串内部的所有内容\

"{\"title\":\"MyApp Companion\", ... }"

回答by Andrew

Try this:

试试这个:

$.parseJSON('{"title":"MyApp Companion","push_hash":"ff06b5b775e45409f9ab470b64d672d0","t":"mr","alert":"Ryjjgv","n":"Foo Bar","action":"open the app at specific location","pid":"7V8meRCJaj","badge":"Increment"}')