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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.