Home  >  Article  >  Web Front-end  >  Common methods for manipulating JSON using JS (practical, graphic tutorials)

Common methods for manipulating JSON using JS (practical, graphic tutorials)

亚连
亚连Original
2018-05-18 15:15:251640browse

1. Concept introduction

JSON (JavaScript Object Notation) is a lightweight data exchange format that uses a complete Language-independent text format ideal for data exchange. At the same time, JSON is a JavaScript native format, which means that processing JSON data in JavaScript does not require any special API or toolkit.
In JSON, there are two structures: objects and arrays.

##1.Object

var packJson = {"name":"Liza", "password":"123"};

An object starts with "{" and ends with "}", and "," is used to separate "key/value".

2.array

var packJson = [{"name":"Liza", "password":"123"}, {"name":"Mike", "password":"456"}];

##array is an ordered collection of values. An array starts with "[" and ends with "]". Use "," to separate values.

二、JSON对象和JSON字符串的转换

在数据传输过程中,JSON是以字符串的形式传递的,而JS操作的是JSON对象,所以,JSON对象和JSON字符串之间的相互转换是关键。例如:

JSON字符串:

var jsonStr ='{"name":"Liza", "password":"123"}' ;

JSON对象:

var jsonObj = {"name":"Liza", "password":"123"};

1、JSON字符串转化JSON对象

var jsonObject= jQuery.parseJSON(jsonstr);

2、JSON对象转化JSON字符串

var jsonstr =JSON.stringify(jsonObject );

三、JSON的输出美化

JSON.stringify(value[, replacer [, space]])
上一节讲到了将JSON转化为字符串可以用JSON.stringify() 方法,stringify还有个可选参数space,可以指定缩进用的空白字符串,用于美化输出(pretty-print);
space参数是个数字,它代表有多少的空格;上限为10。该值若小于1,则意味着没有空格;如果该参数没有提供(或者为null)将没有空格。

我们看下代码:

var formatJsonStr=JSON.stringify(jsonObject,undefined, 2);
待美化的JSON:
美化后的效果:

四、JSON字符串的替换

工作经常遇到这样的字符串,如下:
需要经过替换后,才能从字符串转化成JSON对象。这里我们需要用JS实现replaceAll的功能, 将所有的 ' \\" ' 替换成  ' " ' .

代码如下,这里的gm是固定的,g表示global,m表示multiple:

var jsonStr=jsonStr.replace(new RegExp('\\"',"gm"), '"' );
替换后的效果如下:

五、遍历JSON对象和JSON数组

1、遍历JSON对象代码如下:

var packJson  = {"name":"Liza", "password":"123"} ;  
for(var k in packJson ){//遍历packJson 对象的每个key/value对,k为key
   alert(k + " " + packJson[k]);  
}

2、遍历JSON数组代码如下:

var packJson = [{"name":"Liza", "password":"123"}, {"name":"Mike", "password":"456"}];  
for(var i in packJson){//遍历packJson 数组时,i为索引
   alert(packJson[i].name + " " + packJson[i].password);  
}

六、递归遍历

为了实现一些复杂功能常常需要递归遍历JSON对象,这里给出两个递归的例子,希望能给大家参考递归的写法。
1、第一个例子是递归遍历JSON,遇到数组的时候,数组中有超过一个对象,删除第一个对象之后的所有对象
举个例子,原始JSON如下:
期望处理后的JSON如下:

递归代码如下:

/** 
 *返回处理后的 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]);  
      } elseif(obj instanceof Object) {  
             for( var index in obj){  
                   var jsonValue = obj[index];  
                  distinctJson(jsonValue);  
            }  
      }  
}
2、第二个例子是递归查找目标节点(节点id为targetId,有且只有一个),找到后把targetChildren赋值给节点的children,
举个例子,原始JSON如下,查找的目标节点id为5:
targetChildren为
期望最后处理的JSON结果为:

递归代码如下:

/** 
 * 递归查找目标节点 
 */
function findTarget(obj,targetId,targetChildren){  
    if(obj.id==targetId){  
          obj.children=targetChildren;  
          returntrue;  
    }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){  
                          returntrue;  
                    }  
               }  
          }  
    }  
    returnfalse;  
}

上面是我整理给大家的JS操作JSON常用方法,希望今后会对大家有帮助。

相关文章:

JavaScript使用forEach()与jQuery使用each遍历数组时return false 的区别

JavaScript实现把rgb颜色转换成16进制颜色的方法

详细了解JavaScript Array 对象的基本内容

The above is the detailed content of Common methods for manipulating JSON using JS (practical, graphic tutorials). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn