I am doing some site crawling, and right now, I find this string of a JSON object
{ "results" : [
{
id: 775664,
status: "In-Stock",
ffmtCenterId: '10601',
altText: "In-Stock",
qty: 6
}
]}
and I wan't to convert that to a object using JSON.parse()
but this doesn't work because there are syntax errors, like you need quotes around the key values. I tried eval()
but it didn't work.
Does anyone know whats a good way to fix this string so that I can convert it into an object?
Thanks
how did you try eval()
?
eval("var a = " + incoming_string);
var fixed = JSON.stringify(a);
a
is the object, I don't think you need that fixed
string.
Of course, eval an unknown string is not safe.
The hjson project seems to be a possible solution. Thier online converter managed to parse your broken structure into proper JSON though there seem to be some quirks in the conversion.
Though I see you've commented that you've already found a fix, here's a double replace()
that worked on this sample as a multiline string:
var a = `{ "results" : [
{
id: 775664,
status: "In-Stock",
ffmtCenterId: '10601',
altText: "In-Stock",
qty: 6
}
]}`
var b = a.replace(/(\w+)(: )/g, "\"$1\" $2" ).replace(/(:\s+)['](\w+)['](,\n)/g, "$1\"$2\"$3" )
var jo = JSON.parse( b )
Without the 2nd replace()
, I was getting JSON.parse errors in Firebug on the ffmtCenterId
data.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.