Home > Web Front-end > JS Tutorial > body text

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

亚连
Release: 2018-05-18 15:15:25
Original
1692 people have browsed it

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"};
Copy after login

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"}];
Copy after login

##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"}' ;
Copy after login

JSON对象:

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

1、JSON字符串转化JSON对象

var jsonObject= jQuery.parseJSON(jsonstr);
Copy after login

2、JSON对象转化JSON字符串

var jsonstr =JSON.stringify(jsonObject );
Copy after login

三、JSON的输出美化

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

我们看下代码:

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

四、JSON字符串的替换

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

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

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

五、遍历JSON对象和JSON数组

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

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

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);  
}
Copy after login

六、递归遍历

为了实现一些复杂功能常常需要递归遍历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);  
            }  
      }  
}
Copy after login
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;  
}
Copy after login

上面是我整理给大家的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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template