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.
Your best and safest bet would be JSON5 – JSON for Humans. It is created specifically for that use case.
Maybe you have to try this:
var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }" var fStr = str .replace(/([A-z]*)(:)/g, '"$1":') .replace(/'/g, "\"")
console.log(JSON.parse(fStr))
Sorry I am on my phone, here is a pic.
Just for the quirks of it, you can convert your string via
babel-standalone
Your string is not valid JSON, so
JSON.parse
(or jQuery's$.parseJSON
) won't work.One way would be to use
eval
to "parse" the "invalid" JSON, and thenstringify
it to "convert" it to valid JSON.I suggest instead of trying to "fix" your invalid JSON, you start with valid JSON in the first place. How is
str
being generated, it should be fixed there, before it's generated, not after.EDIT: You said (in the comments) this string is stored in a data attribute:
I suggest you fix it here, so it can just be
JSON.parse
d. First, both they keys and values need to be quoted in double quotes. It should look like (single quoted attributes in HTML are valid):Now, you can just use
JSON.parse
(or jQuery's$.parseJSON
).