Principle and Example Analysis of JSON stringify Method

  • 2021-08-31 07:22:14
  • OfStack

The JSON. stringify () method is used to convert an JavaScript value to an JSON string.

Grammar

JSON.stringify(value[, replacer[, space]])

Parameter description:

value:

Required, JavaScript value to be converted (usually an object or array).

replacer:

Optional. The function or array used to convert the result.

If replacer is a function, JSON. stringify calls the function and passes in the key and value of each member. Use the return value instead of the original value. If this function returns undefined, members are excluded. The key of the root object is an empty string: "".

If replacer is an array, only members of the array with key values are converted. The conversion order of members is the same as that of keys in an array.

space:

Optional, text is indented, with spaces, and newlines. If space is 1 number, the return value text is indented by a specified number of spaces at each level, and if space is greater than 10, the text is indented by 10 spaces. space can also use non-digits, such as\ t.

Return value:
Returns a string containing JSON text.

Instances


var str = {"name":" Rookie tutorial ", "site":"http://www.runoob.com"}
str_pretty1 = JSON.stringify(str)
document.write( " Only 1 Parameter conditions: " );
document.write( "<br>" );
document.write("<pre>" + str_pretty1 + "</pre>" );
 
document.write( "<br>" );
str_pretty2 = JSON.stringify(str, null, 4) // Use 4 Spaces indent 
document.write( " Parameters used: " );
document.write( "<br>" );
document.write("<pre>" + str_pretty2 + "</pre>" ); // pre  Used to format output 

However, there is no JSON object under IE6-7, so it should be implemented with json2.js.

Today, let's briefly introduce some correct postures of stringify method.

Of course, let the masters laugh cheaply. This article just shares some methods for novice friends.


var data = [
  {name: " Wang Nima ", sex:1, age: 30},
  {name: " Wang Nimei ", sex:0, age: 20},
  {name: " Wang Dachui ", 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 complicated, and there are information like avatars, nicknames and personal signatures.
But I save it locally, only need the user name and gender, is it swollen?
Maybe you will say so easy, traverse the data and extract it again.
For example:


var data = [
  {name: " Wang Nima ", sex:1, age: 30},
  {name: " Wang Nimei ", sex:0, age: 20},
  {name: " Wang Dachui ", 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's done in minutes.

In fact, we only need to use the second parameter of stringify to simply deal with this problem.


var data = [
  {name: " Wang Nima ", sex:1, age: 30},
  {name: " Wang Nimei ", sex:0, age: 20},
  {name: " Wang Dachui ", sex:1, age: 30}
];
var str_json = JSON.stringify(data, ["name", "sex"]);
console.log(str_json);

As long as the second parameter passes in the required keys array, it is very easy to complete this processing.

Of course, if we have to deal with more entanglement, such as changing 1 and 0 to male and female, then the second parameter can be handled by callback function.


var data = [
  {name: " Wang Nima ", sex:1, age: 30},
  {name: " Wang Nimei ", sex:0, age: 20},
  {name: " Wang Dachui ", 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 tough that it saves us a lot of trouble.

There is also a third parameter, which is used to format the string.


var data = [
  {name: " Wang Nima ", sex:1, age: 30},
  {name: " Wang Nimei ", sex:0, age: 20},
  {name: " Wang Dachui ", 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 rib function, but it is useless under normal circumstances.

Ok, that's all for today's sharing. I hope it will be helpful to novice friends.


Related articles: