Convert object string to JSON

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).

Leave a Comment