Subhashi
Subhashi

Reputation: 4081

Parsing JSON with backslash node.js

I have this JSON file,

{
  "file_paths": {
    "PROCESS": "C:\incoming",
    "FAILED": "C:\failed"
  }
}

I get an error when I try to access PROCESS or FAILED. The error is SyntaxError: Unexpected token i in JSON. It must be due to backslash. How can I access PROCESS or FAILED without editing the JSON file?

Upvotes: 1

Views: 1015

Answers (3)

Jesse
Jesse

Reputation: 2074

You will need to escape the backslash in your JSON String.

If you are building the JSON yourself, you can escape special characters when you build it. OR if you are not, as a post process once you have the JSON file you could do something like sed over it to replace the backslash with an escaped backslash (obviously not the ideal solution).

Upvotes: 1

rickjerrity
rickjerrity

Reputation: 814

As J Livengood said, you need to escape backslashes when inside a string. Like so:

var obj = {
  "file_paths": {
    "PROCESS": "C:\\incoming",
    "FAILED": "C:\\failed"
  }
}

Upvotes: 1

J Livengood
J Livengood

Reputation: 2738

The reason is because the JSON is not valid do to the \ no being escaped making the reader think the i is trying to be escaped

Upvotes: 1

Related Questions