1

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?

1
  • Try posting a demo, there is a button in the toolbar to demonstrate your issue. Or try jsfiddle.net Commented Jul 6, 2015 at 4:03

2 Answers 2

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.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");
Sign up to request clarification or add additional context in comments.

2 Comments

thanks but this is actually not about "\n" problem. What I posted was a JSON data, not a string. I tried removing it and there was the same error. I think the problem is in the key "description" because it ran fine when I delete the last space in "Weekly Bullets (20 minutes): "
@HưngCaoXuân in that case you need to share your complete code... like the isString() method and a way to recreate the issue
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.