1

I have a valid JSON:

{"name":"tono","html":"<p><a href=\"http:\/\/someurl.com\">Here<\/a> is the link<\/p>"}  

But, when I parse it through javascript (I use firefox's console)

JSON.parse('{"name":"tono","html":"<p><a href=\"http:\/\/someurl.com\">Here<\/a> is the link<\/p>"}');

I get this error

SyntaxError: JSON.parse: expected ',' or '}' after property value in object at line 1 column 36 of the JSON data

Is it an expected behavior? And how to parse JSON which contains URL correctly?

Just for additional information, this one works:

JSON.parse('{"name":"tono","html":"<p><a href=>Here<\/a> is the link<\/p>"}');

Object { name: "tono", html: "<p><a href=>Here</a> is the link</p>" }

More additional information:

The JSON parsed flawlessly here: http://jsonviewer.stack.hu

12
  • 1
    @TravisJ it is valid. Commented Oct 5, 2015 at 22:14
  • 1
    @TravisJ JSONLint say's it's valid. Commented Oct 5, 2015 at 22:14
  • 1
    (There's no need to backslash-escape the forward slashes.) Commented Oct 5, 2015 at 22:14
  • 1
    Why are forward slashes escaped Commented Oct 5, 2015 at 22:17
  • 1
    @Barmar Thanks for that. It's an edge case, certainly, but worth knowing about. Commented Oct 5, 2015 at 22:20

2 Answers 2

3

Escape the backslashes in a string literal so they'll be treated literally.

console.log(JSON.parse('{"name":"tono","html":"<p><a href=\\"http:\\/\\/someurl.com\\">Here<\\/a> is the link<\\/p>"}'));

The reason why the forward slashes are escaped is explained here JSON: why are forward slashes escaped?

Sign up to request clarification or add additional context in comments.

2 Comments

I updated the answer to add a link to the reason for the redundant escapes
It may be redundant, but it works :) And the URL is worth to read.
-2

As Barmar explained, you can escape the backslashes like such.

JSON.parse('{"name":"tono","html":"<p><a href=\\"http://someurl.com\\">Here</a> is the link</p>"}');

3 Comments

barmar explained it, so why are you?
Look: jsfiddle.net/yjedwLws you will see what's wrong. it completey messes up the url.
@Pamblam I don't see anything wrong with the output. Are you sure you understand what JSON.stringify does?

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.