最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript cannot parse JSON string - Stack Overflow

programmeradmin2浏览0评论

I was trying to parse this JSON string:

{"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): "]}

This is a valid JSON (checked on jsonformatter.curiousconcept). However, I received erorr:

SyntaxError: Unexpected token

in (file angular.js):

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

Anyone has ideas?

I was trying to parse this JSON string:

{"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): "]}

This is a valid JSON (checked on jsonformatter.curiousconcept.). However, I received erorr:

SyntaxError: Unexpected token

in (file angular.js):

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

Anyone has ideas?

Share Improve this question asked Jul 6, 2015 at 4:02 Hưng Cao XuânHưng Cao Xuân 351 silver badge5 bronze badges 1
  • Try posting a demo, there is a button in the toolbar to demonstrate your issue. Or try jsfiddle – elclanrs Commented Jul 6, 2015 at 4:03
Add a ment  | 

2 Answers 2

Reset to default 4

The problem is the \n in the text, you need to escape it to \\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./a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


<script src="https://ajax.googleapis./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:

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

Here you are, a \n token in your string, let remove it:

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.

发布评论

评论列表(0)

  1. 暂无评论