1

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?

3 Answers 3

1

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).

Sign up to request clarification or add additional context in comments.

3 Comments

I cannot actually edit the file and it is created previously.
I am not proposing you manually edit the file. I am saying if you are using in a linux environment use the sed utility that parses and transforms text. sed 's/{{find}}/{{replace}}/g' {{filename}}
Just to add (which you probably already figured out) sed 's-\\-\\\\-g' {{filename}}
1

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

1 Comment

yes. the error occurs due to '\'. Is there any way to read it omitting the '\'?
1

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"
  }
}

3 Comments

but that means I will have to edit the JSON file? Is there a way to do it without editing the file?
Check Jesse's answer. You'd have to edit the JSON file at some point before parsing it, no way around that. As Jesse mentioned, you'd have to do something like read the JSON file into a temporary file you have read/write access to. Modify any instance of "\" to "\\", then read the temp file you created and dispose of it afterwards
That was a good method. I tried to change the same file and it did not work as recursively it changed '/' with '//' and after a few times ended up with '//////'. Writing it to a different file worked perfectly. Thank you all...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.