Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError: Unexpected token \ in JSON at position

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.

like image 452
Michael Nielsen Avatar asked Jan 27 '17 08:01

Michael Nielsen


People also ask

How do I fix unexpected token in JSON at position?

Those who are using create-react-app and trying to fetch local json files. SyntaxError: Unexpected token < in JSON at position 0. To solve this, you need to eject the app and modify the webpack-dev-server configuration file.

What does SyntaxError unexpected token in JSON at position 0?

Re: Unexpected token in JSON at position 0 This usually means that an error has been returned and that's not valid JSON. Check the browser developer tools console and network tabs. Turn on Debugging and (after reproducing the error) check the web server error logs.

How do I fix an unexpected token?

As you write your JavaScript application, the unexpected token error always occurs because JavaScript expected a specific syntax that's not fulfilled by your current code. You can generally fix the error by removing or adding a specific JavaScript language symbol to your code.

What does position mean in JSON?

The position in the error message indicates which byte within the file the error occurs around.


1 Answers

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.

like image 178
T.J. Crowder Avatar answered Oct 03 '22 20:10

T.J. Crowder