5

I'm trying to parse a String to JSON in NodeJS/Javascript, this is my string (which I cannot change, coming from an external database):

'{\\"value1\\":\\"XYZ\\",\\"value2\\":\\"ZYX\\"}'

I'm calling:

JSON.parse(row.raw_data)

But are getting:

SyntaxError: Unexpected token \ in JSON at position

I actually thought double escape was the correct way of escaping in string/JSON.

1 Answer 1

9

Your JSON is invalid. You've said you can't change it, which is unfortunate.

It looks like it's been double-stringified but then the outermost quotes have been left off. If so, you can fix it by adding " at each end and then double-parsing it, like this:

var str = '{\\"value1\\":\\"XYZ\\",\\"value2\\":\\"ZYX\\"}';
str = '"' + str + '"';
var obj = JSON.parse(JSON.parse(str));
console.log(obj);

Ideally, though, you'll want to go through the database and correct the invalid data.

I actually thought double escape was the correct way of escaping in string/JSON.

In JSON, strings are wrapped in double quotes ("), not double escapes. You only escape double quotes within strings (with a single \).

If you've been creating JSON strings manually (in code), don't. :-) Instead, create the structure you want to save, and then stringify it. Building JSON strings manually is error-prone, but a proper JSON stringifier will be reliable.

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

1 Comment

I initially thought of cutting the backslahes away using a regex, but your solution is way better. So I cancelled writing my own answer, and can only say: upvote :-)

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.