Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON having back slashes - Javascript

I've big JSON something like this:

{
  "EmployeeMaster": {
    "ImageContent": null,
    "ImageName": null,
    "EMP_PhotoPath": "E:\BBM0000000001comparison.png"
  }
}

I'm trying to parse it, but its not working due to slash in EMP_PhotoPath.

How can resolve this error ?

like image 676
Mox Shah Avatar asked Feb 16 '17 18:02

Mox Shah


2 Answers

var jsonString = String.raw`{"EmployeeMaster":{"ImageContent":null,"ImageName":null,"EMP_PhotoPath":"E:\BBM0000000001comparison.png"}}`;
jsonString = jsonString.replace("\\","\\\\");
var jsonObj = JSON.parse(jsonString);
alert(jsonObj.EmployeeMaster.EMP_PhotoPath);

You can Achieve this by doing something like this:

var jsonString = String.raw`{"EmployeeMaster":{"ImageContent":null,"ImageName":null,"EMP_PhotoPath":"E:\BBM0000000001comparison.png"}}`;
jsonString = jsonString.replace("\\","\\\\");
var jsonObj = JSON.parse(jsonString);

String.raw is a method you can use to get the original string without interpretation,

It's used to get the raw string form of template strings (that is, the original, uninterpreted text).

So you can replace the backslash with double backslashes, then you can parse it to keep the original backslash.

like image 190
Ryad Boubaker Avatar answered Oct 23 '22 14:10

Ryad Boubaker


You have to escape the slash with a second slash. Your valid json would look like that:

{
    "EmployeeMaster": {
        "ImageContent": null,
        "ImageName": null,
        "EMP_PhotoPath": "E:\\BBM0000000001comparison.png"
    }
}

ps: Paste it into JSONLint.com to verifiy.

like image 35
geraldo Avatar answered Oct 23 '22 15:10

geraldo