js中的有效JSON文件格式

时间:2016-06-06 11:58:37

标签: javascript json parsing

我想控制给定数据是否为JSON格式。 对于此控件,我使用try JSON.parse。作为;

var str= {
  "employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
  ]
}
try {
  parsed = JSON.parse(str);
} catch (err) {
    return "It is not valid JSON file";
}

但我想延长规则。 我想接受以下文件格式,其中字段不必写在“”as;

{
 employees:[
  {firstName:"John", lastName:"Doe"},
  {firstName:"Anna", lastName:"Smith"},
  {firstName:"Peter", lastName:"Jones"}
 ]
}

我该怎么做? JSON.parse不接受此格式。

2 个答案:

答案 0 :(得分:0)

您可以尝试清理字符串并手动添加"

var str = '{name: "alex" , age: "33"}';
var d= '{employees:[{firstName:"John",lastName:"Doe"},{firstName:"Anna",lastName:"Smith"},{firstName:"Peter",lastName:"Jones"}]}';

function processObject(str){
  var spaceReg = /\s/g;
  var _str = str.replace(spaceReg, "");
  
  var quoteReg = /\"/g;
  _str = _str.replace(quoteReg, "");
  
  var startBrace = /{/g;
  _str = _str.replace(startBrace,"{\"");
  
  var endBrace = /}/g;
  _str = _str.replace(endBrace,"\"}");
  
  var colon = /:/g
  _str = _str.replace(colon,"\":\"");
  
  var comma = /,/g
  _str = _str.replace(comma,"\",\"");
  
  var endBraceStr = /}\"/g
  _str = _str.replace(endBraceStr,"}");
  
  var startBraceStr = /\"{/g
  _str = _str.replace(startBraceStr,"{");
  
  var endBraceArrStr = /\]\"/g
  _str = _str.replace(endBraceArrStr,"]");
  
  var startBraceArrStr = /\"\[/g
  _str = _str.replace(startBraceArrStr,"[");
  
  console.log(_str)
  
  return JSON.parse(_str);
}

console.log(processObject(str))
console.log(processObject(d))

答案 1 :(得分:0)

JSON.parse必须应用于JSON字符串,而不是JSON对象。