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

Vue opens a new window and implements a graphic example of parameter transfer

The function I want to achieve is to open a new w...

Implementing Priority Queue in JavaScript

Table of contents 1. Introduction to priority que...

Solution to the problem that elements with negative z-index cannot be clicked

I was working on a pop-up ad recently. Since the d...

Analysis of the difference between emits and attrs in Vue3

Table of contents in conclusion Practice Analysis...

Example of using swiper plugin to implement carousel in Vue

Table of contents vue - Use swiper plugin to impl...

CentOS 8.0.1905 installs ZABBIX 4.4 version (verified)

Zabbix Server Environment Platform Version: ZABBI...

Vue implements student management function

This article example shares the specific code of ...

Vue v-model related knowledge summary

​v-model is a Vue directive that provides two-way...

Mysql splits string into array through stored procedure

To split a string into an array, you need to use ...

Solution to Vue3.0 error Cannot find module'worker_threads'

I'll record my first attempt at vue3.0. When ...

A brief discussion on several situations where MySQL returns Boolean types

mysql returns Boolean type In the first case, ret...

Complete steps to implement location punch-in using MySQL spatial functions

Preface The project requirement is to determine w...

Solution to mysql error when modifying sql_mode

Table of contents A murder caused by ERR 1067 The...

Implementation code of jquery step progress axis plug-in

A jQuery plugin every day - step progress axis st...