14

I have been trying to figure out why the following JSON input will be failed to parse in JSON.parse function.

{"World":"Hello\\Test"}

The json above is being returned by JSON.NET.

I have tried multiple methods to get this working. As you can see the backslash is escaped and https://jsonlint.com/ is able to parse it.

I have a failing sample at https://jsfiddle.net/ckp0uc0p/3/ as well.

Any help will be appreciated.

6
  • Possible duplicate of Why does the jQuery JSON parser need double escaping for backslashes? Commented May 3, 2017 at 20:34
  • Unfortunately, I do not control the data. I tagged JSON.NET as this data seems to be parsed by that component and stored in that fashion. Commented May 3, 2017 at 20:43
  • The JSON you posted is valid. How exactly are you trying to parse it? Are you really injecting it into the JavaScript source as a string literal as shown in your example? Commented May 3, 2017 at 21:08
  • @FelixKling yes, I basically run exactly what is sent in the JSFiddle URL. The thing is, it is stored just like that in the DB after getting serialized by JSON.NET, therefore, I am just retrieving it and I do not really want to go on a replace route for the "\\" vs "\\\\". Commented May 3, 2017 at 21:09
  • 1
    @FelixKling that did work. Thanks! Commented May 3, 2017 at 21:16

3 Answers 3

7

The best way to inject JSON into JavaScript source code (when generating the JavaScript with a server side language), is to inject it directly where you need it, not inside a string literal that needs to be parsed.

For example:

var foo = <json blob>;

so that the result will be

var foo = {"World":"Hello\\Test"};

JavaScript will interpret this as an object literal resulting in an object, which is what you want to get anyway. This avoids all the problems with "nested" escape sequences.

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

Comments

6

You need to add two \\ for every backslash you want to have it displayed. If you're parsing a json, to display 2 backslashes you need to add 4.

// inside a string to be parsed as json
var json = '{"World":"Hello\\\\Test"}'
console.log(JSON.parse(json))

// directly in an object
var object = {"World": "Hello\\Test"}
console.log(object)

1 Comment

what if you want only one backslash? this fails: var s = JSON.parse('{"World":"Hello\\Test"}');
1

try
{
  var res = '{"World":"Hello\\\\Test"}';
	var s = JSON.parse(res);
  console.log(JSON.stringify(s));
  
} catch(error) {
	alert(error);
}

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.