It should be known that using JSON, it is very common to put an object through stringify and then submit it to the background or store it in Storage .
However, there are no JSON objects under ie6-7, so use json2.js to implement them.
Today, let's briefly introduce some of the correct use posture of the stringify method.
Of course, let the experts laugh, this article is just to share some methods to the novice friends.
var data = [ {name: "Wang Nima", Sex:1, age:30}, {name: "Nebuchadrezzar Beauty", sex:0, age:20}, {name: "King Sledgehammer", Sex:1, Age:30}];var Str_json = json.stringify (data); Console.log (Str_json);
This is our daily usage, very simple, right.
Our data, for example, is very complex, with information like avatars, nicknames, personal signatures, and so on.
But I kept in the local, only need the user name, and gender, swollen?
Perhaps you would say so easy, and iterate over the data to retrieve it.
For example:
var data = [ {name: "Wang Nima", Sex:1, age:30}, {name: "Nebuchadrezzar Beauty", sex:0, age:20}, {name: "King Sledgehammer", 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 does take minutes to get it done.
In fact, we just need to use the second parameter of Stringify to deal with this problem simply.
var data = [ {name: "Wang Nima", Sex:1, age:30}, {name: "Nebuchadrezzar Beauty", sex:0, age:20}, {name: "King Sledgehammer", Sex:1, Age:30}];va R Str_json = json.stringify (data, ["name", "Sex"]); Console.log (Str_json);
The second parameter simply passes in the required keys array, which is very easy to do.
Of course, if we want to deal with more entanglements, such as changing the 1,0 to male and female, then the second parameter can be handled with a callback function.
var data = [ {name: "Wang Nima", Sex:1, age:30}, {name: "Nebuchadrezzar Beauty", sex:0, age:20}, {name: "King Sledgehammer", 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 strong that it saves us a lot of trouble.
There is also a third parameter that is used to format the string.
var data = [ {name: "Wang Nima", Sex:1, age:30}, {name: "Nebuchadrezzar Beauty", sex:0, age:20}, {name: "King Sledgehammer", 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 chicken function, and the general situation is not useful.
Well, today's sharing is these, hoping to help the novice friends.
Resources:
Json.stringify ()-JavaScript | MDN
JSON in JavaScript