Table of Contents
1. Concept introduction" >1. Concept introduction
二、JSON对象和JSON字符串的转换" >二、JSON对象和JSON字符串的转换
三、JSON的输出美化" >三、JSON的输出美化
四、JSON字符串的替换" >四、JSON字符串的替换
五、遍历JSON对象和JSON数组" >五、遍历JSON对象和JSON数组
六、递归遍历" >六、递归遍历
Home Web Front-end JS Tutorial Common methods for manipulating JSON using JS (practical, graphic tutorials)

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

May 18, 2018 pm 03:15 PM
javascript json operate

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Linux Deploy operation steps and precautions Linux Deploy operation steps and precautions Mar 14, 2024 pm 03:03 PM

LinuxDeploy operating steps and precautions LinuxDeploy is a powerful tool that can help users quickly deploy various Linux distributions on Android devices, allowing users to experience a complete Linux system on their mobile devices. This article will introduce the operating steps and precautions of LinuxDeploy in detail, and provide specific code examples to help readers better use this tool. Operation steps: Install LinuxDeploy: First, install

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Huawei Mate60 Pro screenshot operation steps sharing Huawei Mate60 Pro screenshot operation steps sharing Mar 23, 2024 am 11:15 AM

With the popularity of smartphones, the screenshot function has become one of the essential skills for daily use of mobile phones. As one of Huawei's flagship mobile phones, Huawei Mate60Pro's screenshot function has naturally attracted much attention from users. Today, we will share the screenshot operation steps of Huawei Mate60Pro mobile phone, so that everyone can take screenshots more conveniently. First of all, Huawei Mate60Pro mobile phone provides a variety of screenshot methods, and you can choose the method that suits you according to your personal habits. The following is a detailed introduction to several commonly used interceptions:

Discuz domain name modification operation guide Discuz domain name modification operation guide Mar 09, 2024 pm 04:36 PM

Discuz Domain Name Modification Operation Guide In the process of using the Discuz forum system, sometimes we need to modify the domain name of the forum. It may be because the domain name needs to be changed, or some domain name resolution problems need to be repaired. This article will introduce in detail how to modify the domain name in the Discuz forum system, and give some specific code examples. 1. Back up data Before performing any operation, we must back up the data to prevent data loss due to operational errors. In Discuz, you can use the background data backup

PHP string manipulation: a practical way to effectively remove spaces PHP string manipulation: a practical way to effectively remove spaces Mar 24, 2024 am 11:45 AM

PHP String Operation: A Practical Method to Effectively Remove Spaces In PHP development, you often encounter situations where you need to remove spaces from a string. Removing spaces can make the string cleaner and facilitate subsequent data processing and display. This article will introduce several effective and practical methods for removing spaces, and attach specific code examples. Method 1: Use the PHP built-in function trim(). The PHP built-in function trim() can remove spaces at both ends of the string (including spaces, tabs, newlines, etc.). It is very convenient and easy to use.

How to bind WeChat on Ele.me How to bind WeChat on Ele.me Apr 01, 2024 pm 03:46 PM

Ele.me is a software that brings together a variety of different delicacies. You can choose and place an order online. The merchant will make it immediately after receiving the order. Users can bind WeChat through the software. If you want to know the specific operation method , remember to check out the PHP Chinese website. Instructions on how to bind WeChat to Ele.me: 1. First open the Ele.me software. After entering the homepage, we click [My] in the lower right corner; 2. Then in the My page, we need to click [Account] in the upper left corner; 3. Then come to the personal information page where we can bind mobile phones, WeChat, Alipay, and Taobao. Here we click [WeChat]; 4. After the final click, select the WeChat account that needs to be bound in the WeChat authorization page and click Just [Allow];

Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Jun 25, 2024 pm 07:09 PM

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

See all articles