json对象中含有null处理方法

单个json对象

var data = {id:"1001",name:"null",age:"10",sex:"null",phone:"null"}

遍历对象判断是null并且设置为想要的值

for(attr in data){        //在遍历对象判断是null并且设置为想要的值
    if(data[attr]==="null")data[attr]='未记录'
}
console.log(data)

输出结果

{id:"1001",name:"未记录",age:"10",sex:"未记录",phone:"未记录"}

请求接口获取到一个json字符串

var data=[
  {id:"1001",name:"null",age:"10",sex:"null",phone:"null"},
  {id:"1002",name:"null",age:"10",sex:"null",phone:"null"},
  {id:"1003",name:"null",age:"10",sex:"null",phone:"null"},
]

遍历对象两次,第二次判断是null并且设置为想要的值

for(attr in data){
    var data2 = data[attr]  //第一次遍历拆成单个json,
    for(attr in data2){        //在遍历对象判断是null并且设置为想要的值
        if(data2[attr]==="null")data2[attr]='未记录'
    }
}
console.log(data2)

输出结果

{id:"1001",name:"未记录",age:"10",sex:"未记录",phone:"未记录"}

你可能感兴趣的:(json对象中含有null处理方法)