-4

I'm trying to parse this string into a JSON:

 "{'firstname':'Jesper','surname':'Aaberg','phone':'555-0100'}"

I'm doing it like so:

var strJSON = "{'firstname':'Jesper','surname':'Aaberg','phone':'555-0100'}";
console.log(JSON.parse(strJSON));

But I get the error message:

VM652:1 Uncaught SyntaxError: Unexpected token ' in JSON at position 1 at JSON.parse ()

Does anybody know what am I missing and how can i solve it?

1
  • 2
    The JSON is invalid. You should use double quotes in it, not single quotes. Commented Nov 10, 2016 at 13:28

4 Answers 4

4

You can replace single quotes to double quotes and parse it.

var str =  "{'firstname':'Jesper','surname':'Aaberg','phone':'555-0100'}";

var o = JSON.parse(str.replace(/\'/g, "\""));
console.log(o)

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

1 Comment

thanks man! that what i'm looking for
3

Single quotes are not valid for strings, you need to use double quotes instead:

var strJSON = '{"firstname":"Jesper","surname":"Aaberg","phone":"555-0100"}';

2 Comments

For clarity, I'd wrap your answer in single quotes, since he does want to parse a string of JSON. I couldn't actually suggest an edit since it was only two characters.
Good point, I made the change.
1

Just change your string:

"{'firstname':'Jesper','surname':'Aaberg','phone':'555-0100'}"

to:

'{"firstname":"Jesper","surname":"Aaberg","phone":"555-0100"}'

JSON only supports double-quotes

Comments

0

var str = '{"firstname":"Jesper","surname":"Aaberg","phone":"555-0100"}';

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

Use this.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.