The 80/20 Guide to json.stringify in JavaScript
Json.stringify () is available in a number of libraries, and is generally supported in modern browsers, even IE8.
Json.stringify () converts a JS object to JSON and can be used with json.parse () as an implementation of deep copy.
Some of the problems you will encounter:
- Loop object => report type error
- Cannot convert correctly, or some values are ignored
// Loop objects
const obj = {};
// Cyclical object that references itself
obj.prop = obj;
// Throws "TypeError: TypeError: Converting circular structure to JSON"
JSON.stringify(obj);
// NaN, Infinity => null
const obj = { nan: parseInt('not a number'), inf: Number.POSITIVE_INFINITY };
JSON.stringify(obj); // '{"nan":null,"inf":null}'
// Ignore functions and undefined
const obj = { fn: function() {}, undef: undefined };
// Empty object. `JSON.stringify()` removes functions and `undefined`.
JSON.stringify(obj); / / '{}'
Copy the code
The loop object is the only case where json.stringify () throws an exception, and even then we need to use a try/catch to catch the exception.
Beautify the output format
Json.stringify () takes three arguments, the third of which is space, which represents the indentation of a few Spaces when it is a number, and the padding of a string when it is a string.
const obj = { a: 1.b: 2.c: 3.d: { e: 4}};JSON.stringify(obj);
// '{"a":1,"b":2,"c":3,"d":{"e":4}}'
JSON.stringify(obj, null.' ');
// Use 2 spaces when formatting JSON output. Equivalent to the above.
JSON.stringify(obj, null.2);
/ / {
// "a": 1,
// "b": 2,
// "c": 3,
// "d": {
// "e": 4
/ /}
// }
JSON.stringify(obj, null.'__');
/ / {
// __"a": 1,
// __"b": 2,
// __"c": 3,
// __"d": {
// ____"e": 4
/ / __}
// }
Copy the code
Custom replacer
Replacer is a callback function that takes key/value and returns the value as the JSON value.
const obj = { a: 1.b: 2.c: 3.d: { e: 4}};JSON.stringify(obj, function replacer(key, value) {
if (typeof value === 'number') {
return value + 1;
}
return value;
});
// `replacer` increments every number value by 1. The output will be:
// '{"a":2,"b":3,"c":4,"d":{"e":5}}'
Copy the code
ToJSON () function
Json.stringify () will iterate over whether the object property has toJSON() and use the return value if it does. ToJSON () can return any value and is ignored if it returns undefined.
const obj = {
name: 'Jean-Luc Picard'.nested: {
test: 'not in output'.toJSON: (a)= > 'test'}};// '{"name":"Jean-Luc Picard","nested":"test"}'
JSON.stringify(obj);
Copy the code
Even with replacer, toJSON
- As long as the return value is
NaN
.Infinity
Shall be converted tonull
- As long as the return value is
function
.undefined
We’re going to ignore them