Hưng Cao Xuân
Hưng Cao Xuân

Reputation: 35

Javascript cannot parse JSON string

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.com). However, I received erorr:

SyntaxError: Unexpected token

in (file angular.js):

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

Anyone has ideas?

Upvotes: 1

Views: 7074

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388326

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.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:

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

Upvotes: 4

hungndv
hungndv

Reputation: 2141

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.

Upvotes: 0

Related Questions