I'm trying to parse a JSON string obtained from an API:
var inputString = '{ "AccountName": "NT AUTHORITY\\SYSTEM"}'
console.log(JSON.parse(inputString)) // View in browser console to see real error
Above code gives error:
Uncaught SyntaxError: Unexpected token S in JSON at position 31 at JSON.parse () at program.html:7
Now below code works:
var inputString = '{ "AccountName": "NT AUTHORITY\\\\SYSTEM"}'
console.log(JSON.parse(inputString))
It shows the output:
{AccountName: "NT AUTHORITY\SYSTEM"}
Backslash character is an escape sequence in JSON. But why do I require four backslashes to create a single backslash? Shouldn't it be only \\
?
The JSON response that I'm getting from the API being called is giving me only two \\
where ever there is a path. So my code is breaking. I believe API's JSON format is correct. When I try to parse this response on online JSON viewer then they are able to parse it successfully.
First, the template literal is parsed. Just like in ordinary strings, a double backslash is translated into a single literal backslash. So, your initial inputString
:
var inputString = `{ "AccountName": "NT AUTHORITY\\SYSTEM"}`
will have a single backslash in it.
console.log(`\\`.length);
Unlike plain Javascript strings (in which unnecessary backslashes are just ignored), JSON format requires that backslashes precede a special character to be escaped (like a "
or another \
). If a backslash and the following character does not translate to an escape character, a SyntaxError
like the one you see in your question will be thrown.
So, to indicate a literal backslash in a JSON, you need two backslashes in the JSON, and to indicate a literal backslash in a Javascript string, you also need two backslashes. Together, you need four backslashes in order to indicate a literal backslash in the JSON.
If you wish to manually write strings that include literal backslashes, and you don't need to use escape characters, you might consider using String.raw
for your template literals, which parse single backslashes as literal backslashes rather than as part of an escape sequence:
console.log(
String.raw`\\`.length
);
const inputString = String.raw`{ "AccountName": "NT AUTHORITY\\SYSTEM"}`;
console.log(JSON.parse(inputString))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With