So I want to create this JSON object:
{
"id":"3",
"created":"0000-00-00",
"parentIDs":null,
"childIDs":"",
"uid":"movies",
"title":"Movies",
"related":"movies",
"pos":"",
"css":"{ "background-image":"-webkit-linear-gradient(bottom, rgb(46,44,46) 49%, rgb(18,17,18) 75%)" }"
}
from string:
value = ""id":"3","created":"0000-00-00","parentIDs":null,"childIDs":"","uid":"imdb","title":"Imdb","related":"movies","pos":"""
This string comes from a database, so I can't really change the formatting, but it should be correct like this.
(This string originates from an array of similiar strings, which I iterate through, somehow losing the {} around them)
I tried removing the outer quotes with value.substr(1, value.length - 2);
. And then convert it with .toJSON();
but it only adds a whole lot of extra slashes I don't need.
I just need to add {}
around it, and then javascript would see it as a JSON object.
Is there any shorthand way of doing that? or is there a small library that can convert my messy string in a clever way to a JSON object?
[update]
I tried: eval('{' + value + '}');
But i get Uncaught SyntaxError: Unexpected token :
in Chrome.
I tried JSON.parse but get: TypeError: JSON.parse is not a function
in Chrome and Firefox, it must be the string's formatting. I'm beginning to suspect the "css" entry, although it starts complaining at the first "id" entry, it's expecting a function instead of JSON?
(I cut down the raw JSON, but forgot the most important "css" one)
[update2]
Ok, so I changed the css data to '
instead of "
, now it will actually parse, but now my script is broken, because I'm expecting raw CSS from the db, any way to change the resulting 'css':'blabla'
to: "css":"blabla"
?
If you have a string that contains valid JSON, you can convert it to a JavaScript Object using JSON.parse()
.
Assuming you have a string:
value = '"id":"3","created":"0000-00-00","parentIDs":null,"childIDs":"","uid":"imdb","title":"Imdb","related":"movies","pos":""';
you would then do:
obj = JSON.parse("{"+value+"}");JSON
Note it needs the {}
as part of the string to be a valid JSON string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With