Convert object string to JSON

snorpey picture snorpey · Jan 27, 2012 · Viewed 578.9k times · Source

How can I convert a string that describes an object into a JSON string using JavaScript (or jQuery)?

e.g: Convert this (NOT a valid JSON string):

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"

into this:

str = '{ "hello": "world", "places": ["Africa", "America", "Asia", "Australia"] }'

I would love to avoid using eval() if possible.

Answer

Matthew Crumley picture Matthew Crumley · Jan 27, 2012

If the string is from a trusted source, you could use eval then JSON.stringify the result. Like this:

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
var json = JSON.stringify(eval("(" + str + ")"));

Note that when you eval an object literal, it has to be wrapped in parentheses, otherwise the braces are parsed as a block instead of an object.

I also agree with the comments under the question that it would be much better to just encode the object in valid JSON to begin with and avoid having to parse, encode, then presumably parse it again. HTML supports single-quoted attributes (just be sure to HTML-encode any single quotes inside strings).