一文解js对json操作

json对象和json字符串区别

对象有对应的属性值,通过 对象.属性名 的方式调用
   var person={"name":"tom","sex":"男","age":"24"}//json对象
   console.log(person.name);//在控制台输出tom
   alert(typeof(person));//object
json字符串是字符串格式符合json格式
  var b='{"name":"2323","sex":"afasdf","age":"6262"}';//json字符串
  console.log(b);//{"name":"2323","sex":"afasdf","age":"6262"}
  alert(typeof(b));//string

对象与字符串之间的转换

字符串转对象
var b='{"name":"2323","sex":"afasdf","age":"6262"}'//json字符串
var bToObject=JSON.parse(b);
console.log(bToObject.name);//2323
对象转字符串
var a={"name":"tom","sex":"男","age":"24"}//json对象
var aToString=JSON.stringify(a);
console.log(aToString);//{"name":"tom","sex":"男","age":"24"}

遍历json对象或者json数组我们可以采用for in的方式

包装方法(返回处理后字符串)

/**
 *返回处理后的 json字符串
 */
function jsonParse(jsonObj) {
     
      distinctJson(jsonObj);
      var last=JSON.stringify(jsonObj, undefined, 2);
      return last;
}
 
 
/**
 * 去掉 json中数组多余的项
 */
function distinctJson(obj) {
      if(obj instanceof Array) {
             if(obj.length > 1) { //数组中有超过一个对象,删除第一个对象之后的所有对象
                  obj.splice(1, (obj.length - 1));
            }
            distinctJson(obj[0]);
      } else if(obj instanceof Object) {
             for( var index in obj){
                   var jsonValue = obj[index];
                  distinctJson(jsonValue);
            }
      }
}

封装代码(查找目标节点)


/**
 * 递归查找目标节点
 */
function findTarget(obj,targetId,targetChildren){
    if(obj.id==targetId){
          obj.children=targetChildren;
          return true;
    }else{
          if(obj.children!=null){
               for(var i=0; i<obj.children.length; i++){
                    var flag=findTarget(obj.children[i],targetId,targetChildren);
                    if(flag==true){
                          return true;
                    }
               }
          }
    }
    return false;
}
发布了71 篇原创文章 · 获赞 21 · 访问量 3647

猜你喜欢

转载自blog.csdn.net/qq_26386437/article/details/104711111