Prateek
Prateek

Reputation: 299

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.

Upvotes: 0

Views: 227

Answers (1)

Shanoor
Shanoor

Reputation: 13692

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>

Upvotes: 2

Related Questions