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 then stringify
it to "convert" it to valid JSON.
var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"
str = JSON.stringify(eval('('+str+')'));
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:
<div data-object="{hello:'world'}"></div>
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):
<div data-object='{"hello":"world"}'></div>
Now, you can just use JSON.parse
(or jQuery's $.parseJSON
).
var str = '{"hello":"world"}';
var obj = JSON.parse(str);
data
-attrubute, like this:<div data-object="{hello:'world'}"></div>
and I don't want to use single quotes in the HTML(so it is probably not to be trusted) – Reputation<div data-object='{"hello":"world"}'></div>
is 100% valid HTML (what does single quotes have to do with trusting it or not?). If you do it this way, you can justJSON.parse
it and it'll work fine. Note: the keys need to be quoted too. – Misstate<div data-object="{\"hello\":\"world\"}"></div>
. If you don't want to use valid JSON in the attribute, then you're gonna have to make your own format and parse it yourself. – Misstate