[英]Whats the cleanest way to repair this JSON object string in javascript?
I am doing some site crawling, and right now, I find this string of a JSON object 我正在进行一些网站爬网,现在,我找到了JSON对象的此字符串
{ "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. 并且我不希望使用JSON.parse()
将其转换为对象,但是由于存在语法错误(例如您需要在键值周围加上引号JSON.parse()
,因此无法正常工作。 I tried eval()
but it didn't work. 我尝试了eval()
但是没有用。
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()
?
eval("var a = " + incoming_string);
var fixed = JSON.stringify(a);
a
is the object, I don't think you need that fixed
string. a
是对象,我认为您不需要该fixed
字符串。
Of course, eval an unknown string is not safe. 当然,评估未知字符串并不安全。
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: 尽管我看到您评论过您已经找到了修复程序,但是这里有一个double replace()
作为多行字符串在此示例上起作用:
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. 没有第二个replace()
,我在ffmtCenterId
数据上的Firebug中收到JSON.parse错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.