Summary of various uses of JSON.stringify

Summary of various uses of JSON.stringify

Preface

Anyone who has used json should know that it is a common method to submit an object to the backend after stringifying it. However, there is no JSON object in IE6-7, so we need to use json2.js to implement it.

1. Classic usage

 var data = [
     {name: "Wukong", sex:1, age: 30},
     {name: "Bajie", sex:0, age: 20},
     {name: "Tang Monk", sex:1, age: 30}
 ]; //The JavaScript array contains objects //Convert the JavaScript object to a string in JSON format var str_json = JSON.stringify(data);
console.log(str_json);
//The result of running is:
//[{"name":"Wukong","sex":1,"age":30},{"name":"Bajie","sex":0,"age":20},{"name":"Tang Monk","sex":1,"age":30}]

So easy! This is also the method we use most often

2. Extraction of complex data

For example, our data is very complex and includes information such as avatars, nicknames, and personal signatures. But I saved it locally and only need the username and gender. How do I do that? We can do this by providing the second parameter, traversing the data and re-extracting it.

a. Traditional way of extracting data

var data = [
    {name: "Wukong", sex:1, age: 30},
    {name: "Bajie", sex:0, age: 20},
    {name: "Tang Monk", sex:1, age: 30}
];
// Traditional way to extract data var new_data = [];
for (var i=0, new_data=[]; i<data.length; i++) {
    //Build the row array new_data.push({
        name: data[i].name,
        sex: data[i].age
    });
}
var str_json = JSON.stringify(new_data);
console.log(str_json);

b. Use the second parameter of stringify to extract data

var data = [
    {name: "Wukong", sex:1, age: 30},
    {name: "Bajie", sex:0, age: 20},
    {name: "Tang Monk", sex:1, age: 30}
];

var str_json = JSON.stringify(data,["name","age"]);
console.log(str_json);
//Running results	
//[{"name":"Wukong","age":30},{"name":"Bajie","age":20},{"name":"Tang Monk","age":30}]

As long as the second parameter passes in the required keys array, this processing can be completed very easily.

Of course, if we want to handle it more complicatedly, such as changing 1,0 to male or female, then the second parameter can be processed by a callback function.

var data = [
    {name: "Wukong", sex:1, age: 30},
    {name: "Bajie", sex:0, age: 20},
    {name: "Tang Monk", sex:1, age: 30}
];

var str_json = JSON.stringify(data,function (key, value) {
    if(key==="sex"){
        return ["Boy","Girl"][value];
    }
    return value;
});
console.log(str_json);
// [{"name":"Wukong","sex":"female","age":30},{"name":"Bajie","sex":"male","age":20},{"name":"Tang Monk","sex":"female","age":30}]

3. The third parameter "Wu Yong"

A very useless parameter, basically never used, depends on your own situation!

var data = [
    {name: "Wukong", sex:1, age: 30},
    {name: "Bajie", sex:0, age: 20},
    {name: "Tang Monk", sex:1, age: 30}
];

var str_json = JSON.stringify(data,["name","sex"],"\t");
console.log(str_json);
/*
[
	{
		"name": "Wukong",
		"sex": 1
	},
	{
		"name": "Bajie",
		"sex": 0
	},
	{
		"name": "Tang Monk",
		"sex": 1
	}
]
*/

If you don't understand, please check the api

developer.mozilla.org/en-US/docs/…

Summarize

This is the end of this article about the usage of JSON.stringify. For more relevant content on the usage of JSON.stringify, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Summary of how JS operates on pages inside and outside Iframe
  • How to make if judgment in js as smooth as silk
  • Implementation of a simplified version of JSON.stringify and its six major features explained in detail
  • Vue implements online preview of PDF files (using pdf.js/iframe/embed)
  • Summary of JavaScript JSON.stringify() usage
  • Detailed explanation of how to solve the circular reference problem encountered when using JSON.stringify
  • The difference and use of json.stringify() and json.parse()
  • Selenium+BeautifulSoup+json gets the json data in the Script tag
  • About if contains comma expression in JavaScript

<<:  MySQL 8.0.15 installation and configuration method graphic tutorial

>>:  Solution to the problem of Access denied for user'root'@'localhost' (using password: YES) in MySQL 8.0 login under win10

Recommend

Reasons and solutions for MySQL sql_mode modification not taking effect

Table of contents Preface Scenario simulation Sum...

Analysis of the principle of Nginx using Lua module to implement WAF

Table of contents 1. Background of WAF 2. What is...

A brief discussion on DDL and DML in MySQL

Table of contents Preface 1. DDL 1.1 Database Ope...

How to get USB scanner data using js

This article shares the specific process of js ob...

Beginners learn some HTML tags (3)

Related articles: Beginners learn some HTML tags ...

Detailed explanation of how to use $props, $attrs and $listeners in Vue

Table of contents background 1. Document Descript...

Will Update in a Mysql transaction lock the table?

Two cases: 1. With index 2. Without index Prerequ...

JS realizes special effects of web page navigation bar

This article shares with you a practical web navi...

IE8 provides a good experience: Activities

Today I had a sneak peek at IE8 beta 1 (hereafter...

Practical record of solving MySQL deep paging problem

Table of contents Preface Why does limit deep pag...

How to change the root user's password in MySQL

Method 1: Use the SET PASSWORD command mysql> ...

How to set up a shared folder on a vmware16 virtual machine

1. Set up a shared folder on the virtual machine:...

What are the image file formats and how to choose

1. Which three formats? They are: gif, jpg, and pn...

Examples of optimistic locking and pessimistic locking in MySQL

The task of concurrency control in a database man...