Syntax Error: Unexpected token \ in JSON at position

I am trying to parse String to JSON in NodeJS / Javascript, this is my string (which I cannot change based on an external database):

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

I'm calling:

JSON.parse(row.raw_data)

But it turns out:

SyntaxError: Unexpected token \ in JSON at position

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

+4
source share
1 answer

Your JSON is invalid. You said you cannot change it, which is unsuccessful.

It looks like he was two-line, but then the most distant quotes were stopped. If so, you can fix it by adding "at each end and then parsing it twice, for example:

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

, , .

, /JSON.

JSON ("), escape-. ( \).

JSON ( ), .:-) , , . JSON , JSON .

+8

Source: https://habr.com/ru/post/1667953/


All Articles