0

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.

5
  • Check the typeof values which you are attempting to parse. It must be string representation of the json Commented Jan 7, 2016 at 8:13
  • 1
    The first stringified array you gave should pass JSON.parse without error and results in an array. Is that indeed your full string you were parsing in your codebase? Commented Jan 7, 2016 at 8:16
  • i too agree with Tao... it works. Commented Jan 7, 2016 at 8:58
  • @Tao P. Rr : my question is not for front-end javascript , I specifically mention it is for nodeJs you can check the below answer for details. Commented Jan 7, 2016 at 10:27
  • @MadhavanKumar : check the below answer Commented Jan 7, 2016 at 10:28

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

replace(/^'|'$/g, '')
@torazaburo Thanks, I forgot about these anchors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.