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.
Use with caution (because of
eval()
):call as:
If the string is from a trusted source, you could use
eval
thenJSON.stringify
the result. Like this: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).
I put my answer for someone who are interested in this old thread.
I created the HTML5 data-* parser for jQuery plugin and demo which convert a malformed JSON string into a JavaScript object without using
eval()
.It can pass the HTML5 data-* attributes bellow:
into the object:
For your simple example above, you can do this using 2 simple regex replaces:
Big caveat: This naive approach assumes that the object has no strings containing a
'
or:
character. For example, I can't think of a good way to convert the following object-string to JSON without usingeval
:Disclaimer: don't try this at home, or for anything that requires other devs taking you seriously:
There, I did it.
Try not to do it tho, eval is BAD for you. As told above, use Crockford's JSON shim for older browsers (IE7 and under)
This method requires your string to be valid javascript, which will be converted to a javascript object that can then be serialized to JSON.
edit: fixed as Rocket suggested.
I hope this little function converts invalid JSON string to valid one.
Result