Mox Shah
Mox Shah

Reputation: 3015

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 ?

Upvotes: 6

Views: 19179

Answers (2)

Ryad Boubaker
Ryad Boubaker

Reputation: 1501

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.

Upvotes: 7

geraldo
geraldo

Reputation: 552

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.

Upvotes: 1

Related Questions