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.
There's a much simpler way to accomplish this feat, just hijack the onclick attribute of a dummy element to force a return of your string as a JavaScript object:
Here's a demo: http://codepen.io/csuwldcat/pen/dfzsu (open your console)
A solution with one regex and not using eval:
This I believe should work for multiple lines and all possible occurrences (/g flag) of single-quote 'string' replaced with double-quote "string".
Use simple code in the link below :
http://msdn.microsoft.com/es-es/library/ie/cc836466%28v=vs.94%29.aspx
and reverse
Douglas Crockford has a converter, but I'm not sure it will help with bad JSON to good JSON.
https://github.com/douglascrockford/JSON-js
You need to use "eval" then JSON.stringify then JSON.parse to the result.
jQuery.parseJSON
Edit. This is provided you have a valid JSON string