Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Parsing error with backslash

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.

like image 988
Hozikimaru Avatar asked May 03 '17 20:05

Hozikimaru


3 Answers

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.

like image 103
Felix Kling Avatar answered Sep 20 '22 08:09

Felix Kling


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)
like image 25
motanelu Avatar answered Sep 18 '22 08:09

motanelu


try
{
  var res = '{"World":"Hello\\\\Test"}';
	var s = JSON.parse(res);
  console.log(JSON.stringify(s));
  
} catch(error) {
	alert(error);
}
like image 27
Devendra Lattu Avatar answered Sep 21 '22 08:09

Devendra Lattu