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.
Text Run
var data = [ "Wang Nima", Sex:-}, "Nebuchadrezzar mei", Sex:"king Sledgehammer", Sex: ()]; 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:
Text Run
var data = [ "Wang Nima", Sex:-}, "Nebuchadrezzar mei", Sex:"king Sledgehammer", Sex: ()]; for (var i=0, new_data=[]; i<data.length; i++) {New_data.push ({name:data[i].name, sex:data[i].sex});} 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.
Text Run
var data = [ "Wang Nima", Sex:-}, "Nebuchadrezzar mei", Sex:"king Sledgehammer", Sex: ()]; Json.stringify (data, ["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.
Text Run
var data = [{name: "Wang Nima", sex:< Span class= "Hljs-number" >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.
Text Run
var data = [ "Wang Nima", Sex:-}, "Nebuchadrezzar mei", Sex:"king Sledgehammer", Sex: ()]; Json.stringify (data, ["\ 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
Category: JavaScript Tags: js, json
Json.stringify method