简体   繁体   中英

NodeJS JSON.parse throwing error

I am simply using JSON.parse in node.js for a array of hexadecimal id

'["5682940386289d593130ed98","568293fe86289d593130ed97","568293f486289d593130ed96"]'

getting an error,

SyntaxError: Unexpected token ' .

Even when i try passing the array as :

'[5682940386289d593130ed98,568293fe86289d593130ed97,568293f486289d593130ed96]'

it throws the error ,

SyntaxError: Unexpected token d .

weird behaviour to understand. Anybody suggestion about where I can read about the same.

Your string starts and ends with a ' for some reason, it actually looks like this:

 // run this snippet // to see the error var str = '\\'["5682940386289d593130ed98","568293fe86289d593130ed97","568293f486289d593130ed96"]\\''; try { JSON.parse(str); } catch (err) { console.log(err); snippet.log(err.stack); } 
 <script src="https://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

I don't know how you build/get this string but you could strip the ending and starting ' from it by using the following code:

 var str = '\\'["5682940386289d593130ed98","568293fe86289d593130ed97","568293f486289d593130ed96"]\\''; str = str.replace(/^'|'$/g, ''); // remove ' before parsing var obj = JSON.parse(str); snippet.log(JSON.stringify(obj)); 
 <script src="https://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM