有如下字符串 (生产上实际很长,testing略精简), 需要转化成js 对象;
var jsonStr= "{comName:企业名称,earliestDeclareDate:最早报关日期,exportCountry1:出口国(地区)1 }";
jsonStr = jsonStr.replace("{", "{\"");
jsonStr = jsonStr.replace(/:/g, "\":\"");
jsonStr = jsonStr.replace(/,/g, "\",\"");
jsonStr = jsonStr.replace("}", "\"}");
// "{"comName":"企业名称","earliestDeclareDate":"最早报关日期","exportCountry1":"出口国(地区)1"}"
JSON.parse(jsonStr);
解析后 {"comName":"企业名称","earliestDeclareDate":"最早报关日期","exportCountry1":"出口国(地区)1"}
ok 搞定。
如果想写的更优雅一点
可以使用 jsonStr.replace(/[{|:|,|}]/,function(value){
let target ;
value==='{' &&(target = "{\"") ;
value ===':' &&(target = "\":\"");
value ===',' &&(target = "\",\"");
value ==='}' &&(target = "\"}") ;
return value ;
})
也可