Emmanuel Villegas Emmanuel Villegas - 28 days ago 17
Javascript Question

how to parse string into json object javascript

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?

Answer

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)