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

Linux bash: ./xxx: Unable to execute binary file error

Today I sent a small tool for Ubuntu to a custome...

Steps to install MySQL 8.0.23 under Centos7 (beginner level)

First, let me briefly introduce what MySQL is; In...

JS implements the snake game

Table of contents 1. Initialization structure 2. ...

Centos7 installation of FFmpeg audio/video tool simple document

ffmpeg is a very powerful audio and video process...

What is a MySQL tablespace?

The topic I want to share with you today is: &quo...

Methods for defragmenting and reclaiming space in MySQL tables

Table of contents Causes of MySQL Table Fragmenta...

MySQL table return causes index invalidation case explanation

Introduction When the MySQL InnoDB engine queries...

js to realize web message board function

This article example shares the specific code of ...

How to use nodejs to write a data table entity class generation tool for C#

Although Microsoft provides T4 templates, I find ...

Detailed explanation of MySQL date string timestamp conversion

The conversion between time, string and timestamp...