简体   繁体   English

Javascript无法解析JSON字符串

[英]Javascript cannot parse JSON string

I was trying to parse this JSON string: 我试图解析此JSON字符串:

{"query": "my schedule today","type": "timeline","title": "Today events:","time":["2015-07-06\\n20:30:00"],"summary":["Weekly meeting + Show & Tell (Hangout)"],"description":["Weekly Bullets (20 minutes): "]} {“ query”:“今天我的日程表”,“ type”:“ timeline”,“ title”:“ Today events:”,“ time”:[“ 2015-07-06 \\ n20:30:00”],“摘要”:[“每周会议+显示并讲述(环聊)”],“说明”:[“每周项目符号(20分钟):”]}

This is a valid JSON (checked on jsonformatter.curiousconcept.com). 这是有效的JSON(已在jsonformatter.curiousconcept.com上选中)。 However, I received erorr: 但是,我收到了erorr:

SyntaxError: Unexpected token 语法错误:意外的令牌

in (file angular.js): 在(文件angular.js)中:

function fromJson(json) {
    return isString(json)
        ? JSON.parse(json)
        : json;
}

Anyone has ideas? 有人有主意吗?

The problem is the \\n in the text, you need to escape it to \\\\n 问题是文本中的\\n ,您需要将其转义为\\\\n

 var json = '{"query": "my schedule today","type": "timeline","title": "Today events:","time":["2015-07-06\\\\n20:30:00"],"summary":["Weekly meeting + Show & Tell (Hangout)"],"description":["Weekly Bullets (20 minutes): "]}' console.log(JSON.parse(json)) snippet.log(JSON.stringify(JSON.parse(json))) 
 <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

If the string you are working with is the result of an external call and you can't change the \\n to \\\\n manually, then this can be achieved with a simple replace: 如果您使用的字符串是外部调用的结果,并且您无法将\\n \\\\n手动更改为\\\\n ,则可以通过简单的替换来实现:

json = json.replace(/\\n/g, "\\\n");

Here you are, a \\n token in your string, let remove it: 在这里,您的字符串中有一个\\n令牌,请删除它:

 var data = '{"query": "my schedule today","type": "timeline","title": "Today events:","time":["2015-07-06\\n20:30:00"],"summary":["Weekly meeting + Show & Tell (Hangout)"],"description":["Weekly Bullets (20 minutes): "]}'.replace('\\n', ''); var data = JSON.parse(data); alert(data.query); 

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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