Introduce a,

One day I encountered a problem: using the json. stringify method to convert an object into a JSON string did not match the expected result. You expect the object to be turned into a JSON string, but you get an empty object.

var myObject = {
  'example': undefined
};
console.log(myObject); // Output {example: undefined}
     
var jsonString = JSON.stringify(myObject);
console.log(jsonString); / / output '{}'
Copy the code

The execution result is shown as follows:

Two, some special values

In the example above, the problem is that when executing json.stringify (obj), if the object contains function, udefined, or null equivalents, the properties with these values will be automatically removed from the object. So it’s safe to use json. stringify when your object contains only strings and numbers.

The good news is that we can use the second argument of json.stringify (obj, replacer) : the replacer function for conversion.

Here’s an example:

var myObject = {
  'property': undefined
};
console.log(myObject);
 
var replacer = function(k, v) { 
	if (v === undefined) { return 'undefined'; } 
    	return v; 
};
var jsonString = JSON.stringify(myObject, replacer);
console.log(jsonString);
Copy the code

The code above creates a replacer function that replaces undefined in the object with the string ‘undefined’.

3. Other values

Similarly, you can use this method if you need to convert other variable types.

Here’s an example:

var myObject = {
    'property': undefined.name: null.fn: function() { console.log('hi')}};console.log(myObject);

var replacer = function (k, v) {
    if (v === undefined) {
        return 'undefined';
    } else if (v === null) {
        return 'null';
    } else if (typeof v === 'function') {
        return v.toString();
    }
    return v;
};

var jsonString = JSON.stringify(myObject, replacer, 2);
console.log(jsonString);
Copy the code

The execution result is as follows:

In addition, the.stringify method has a useful third argument that represents the number of Spaces: space-count, which is used to beautify the output of the JSON string. You can pass the values of 2, 4 ‘\t’, and ‘\n’.

  • Reference: MDN json.stringify ()