JSON. stringify Method
Today, let's briefly introduce some correct positions of the stringify method. Of course, the Experts laughed. This article only shares some methods with new friends. Run var data = [{name: "Wang Nima", sex: 1, age: 30 },{ name: "Wang Nemi", sex: 0, age: 20 }, {name: "", sex: 1, age: 30}]; var str_json = JSON. stringify (data); console. log (str_json); this is our daily usage, which is very simple, right. For example, our data is very complex, and there are information such as portraits, nicknames, and personal signatures. But I save it locally. I only need the user name and gender. Is it swollen? Maybe you will say so easy, just traverse the data and extract it again. For example, run var data = [{name: "Wang Nima", sex: 1, age: 30}, {name: "Wang Nemi", sex: 0, age: 20 },{ name: "", sex: 1, age: 30}]; for (var I = 0, new_data = []; I <data. length; I ++) {new_data.push ({name: data [I]. name, sex: data [I]. sex});} var str_json = JSON. stringify (new_data); console. log (str_json); it is done in minutes. In fact, we can simply solve this problem by using the second stringify parameter. Run var data = [{name: "Wang Nima", sex: 1, age: 30 },{ name: "Wang Nemi", sex: 0, age: 20 }, {name: "", sex: 1, age: 30}]; var str_json = JSON. stringify (data, ["name", "sex"]); console. log (str_json); the second parameter can be easily processed as long as the required keys array is input. Of course, if we want to solve the problem more closely, such as modifying 1, 0 to a male, then the second parameter can be processed using the callback function. Run var data = [{name: "Wang Nima", sex: 1, age: 30 },{ name: "Wang Nemi", sex: 0, age: 20 }, {name: "", sex: 1, age: 30}]; var str_json = JSON. stringify (data, function (k, v) {if (k = "sex") {return ["female", "male"] [v];} return v ;}); console. log (str_json); the second parameter is so powerful that it saves us a lot of trouble. There is also a third parameter for formatting strings. Run var data = [{name: "Wang Nima", sex: 1, age: 30 },{ name: "Wang Nemi", sex: 0, age: 20 }, {name: "", sex: 1, age: 30}]; var str_json = JSON. stringify (data, null, "\ t"); console. log (str_json); str_json = JSON. stringify (data, ["name", "sex"], "\ t"); console. log (str_json); in fact, I think this is a very bad function, but it is generally useless. Well, today's sharing is all about it. I hope it will be helpful to new friends.