7

I'm not able to parse below string as JSON array:

var timeSlots = "['11AM-12PM', '1PM-2PM']";

JSON.parse(timeSlots);

Throws the following error:

VM163:1 Uncaught SyntaxError: Unexpected token ' in JSON at position 1

3
  • 4
    in JSON all Strings use double quotes " single quotes are not valid Commented Oct 7, 2018 at 10:46
  • JSON.parse('["11AM-12PM", "1PM-2PM"]') Commented Oct 7, 2018 at 10:47
  • var timeSlots = '"[\'11AM-12PM\', \'1PM-2PM\']"'; Commented Oct 7, 2018 at 10:51

3 Answers 3

4

In JSON, A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value.

Replace the single quotes with double quotes prefixing the escape (\) character:

var timeSlots = "[\"11AM-12PM\", \"1PM-2PM\"]";

console.log(JSON.parse(timeSlots));

OR: You can simply wrap the string with single quotes which will not require to escape the double quotes:

var timeSlots = '["11AM-12PM", "1PM-2PM"]';

console.log(JSON.parse(timeSlots));

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

Comments

3

Finally, Got the solution

var timeSlots = "['11AM-12PM', '1PM-2PM']";
timeSlots.replace(/'/g, '"');
console.log(JSON.parse(timeSlots));

Comments

1

Try any of these

var timeSlots = "[\"11AM-12PM\", \"1PM-2PM\"]";

or

var timeSlots = '["11AM-12PM", "1PM-2PM"]';

Comments

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.