0

I'm trying to convert a JavaScript string whose value is already formatted in JSON syntax, to a valid JSON object using JSON.parse.

// JSON formatted string
var string = "{'1451893035': 1.2,'1452670635':0.5,'1451720235': 2.5}";
// parse to JSON object
console.log(JSON.parse(string));

I'm currently getting this error:

Uncaught SyntaxError: Unexpected token '

4
  • You need to use double quotes " Commented Jan 17, 2016 at 1:02
  • I'm using double quotes to declare the string value, and single quotes within the string. Commented Jan 17, 2016 at 1:03
  • I know, you need to use double quotes to wrap the keys. Commented Jan 17, 2016 at 1:03
  • for starters...where do you get the string from? Chances are problem can be simplified at the source. Most programming languages will do all the needed serialization for you Commented Jan 17, 2016 at 1:25

1 Answer 1

5
{'1451893035': 1.2,'1452670635':0.5,'1451720235': 2.5}

isn't valid JSON. You want:

{"1451893035": 1.2,"1452670635":0.5,"1451720235": 2.5}
Sign up to request clarification or add additional context in comments.

3 Comments

Ahh, thanks! So JSON just can't handle single 'quotations'
Use a real JSON encoder to encode JSON. JSON is a lot stricter than Javascript, and manually-assembled JSON always ends up in catastrophe.
I can approve of "don't write your own JSON encoder", but "don't write your own JSON"? That's silly.

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.