Home > database >  JSON.parse failing if file path has \\u
JSON.parse failing if file path has \\u

Time:12-29

From a REST API I am receiving a JSON string to which I am trying to parse using JSON.parse(), surprisingly it is failing if within a file path a folder name starts with character u.

For eg.

Consider below JSON:

{"FullPath":"C:\\unitTest\\bcjmail-jdk15to18-1.70.jar"}

This is a valid JSON, but I try to

JSON.parse('{"FullPath":"C:\\unitTest\\bcjmail-jdk15to18-1.70.jar"}');

Then it gives me error JSON.parse: bad Unicode escape at line 1 column 18 of the JSON data and if I modify the folder name unitTest to aunitTest then parsing is successful. Looks like if folder name is starting with character u then it is being considered as \u which is itself a escape character.

How can I solve this?

CodePudding user response:

Backslashes are used as escape characters, and they need to be escaped themselves if they are to be included in the string. You can also replace all backslashes with forward slashes and then parse.

let jsonString = '{"FullPath":"C:/unitTest/bcjmail-jdk15to18-1.70.jar"}';
let obj = JSON.parse(jsonString);
console.log(obj);  // { FullPath: 'C:/unitTest/bcjmail-jdk15to18-1.70.jar' }

OR

let jsonString = '{"FullPath":"C:\\\\unitTest\\\\bcjmail-jdk15to18-1.70.jar"}';
let obj = JSON.parse(jsonString);
console.log(obj);  // { FullPath: 'C:\\unitTest\\bcjmail-jdk15to18-1.70.jar' }

CodePudding user response:

A JSON string must be double-quoted, according to the specs, so you don't need to escape '. If you have to use special character in your JSON string, you can escape it using \ character. So you can try this let s = '{"FullPath":"C:\\unitTest\\bcjmail-jdk15to18-1.70.jar"}' let sr = s.replaceAll('\\','/') JSON.parse(sr)

CodePudding user response:

Try to stringify first

JSON.parse(JSON.stringify({"FullPath":"C:\\unitTest\\bcjmail-jdk15to18-1.70.jar"}))

CodePudding user response:

This is coming already as a JSON format

  • Related