Using a toJSON Method with JSON.stringify

Earlier we demonstrated and described the use of JavaScript's JSON.stringify method as well as how a replacer or filter can be used with JSON.stringify to screen or modify the results. On this page we show how a custom toJSON method can be written for your objects to be applied before JSON.stringify, giving you yet another layer of control.

When you stringify an object or array that has a toJSON method, the toJSON method is called first. The value or object returned by toJSON is then passed to JSON.stringify. The toJSON method can be combined with the replacer or filter argument to JSON.stringify as shown below.

The date object has a built-in toJSON method which converts it to a string when JSON.stringify is invoked. No other object has a built-in toJSON method but you can write them for your objects if you like. We provide an example here:

var obj = {
    min: 2,
    max: 1000,
    bool: true,
    o: null,
    val: undefined,
    re: /^\d+$/,
    fn: function(val) {
        // code here
    },
    m: this.fn,
    // example toJSON method
    toJSON: function(nm) { // arg: object name
        //alert(nm); obj
        var o = {};
        for ( var prop in this ) {
            // convert RegExp to string
            if ( this[prop] && this[prop].constructor == RegExp ) {
                o[prop] = this[prop].toString();
            } else if ( prop == 'm' ) { // function pointer
                o[prop] = 'fn'; // would be removed by stringify otherwise
            } else if ( typeof this[prop] === 'undefined' ) {
                o[prop] = 'undefined'; // would be removed by stringify otherwise
            } else if ( prop === 'bool' ) {
                continue; // don't send to stringify
            } else { // to pass value unchanged
                o[prop] = this[prop];
            }
        }
        return o; // passed to stringify
    }
}
// arguments: obj to stringify, null (no filter or replacer), indent
var json = JSON.stringify(obj, null, 4);
console.log(json);
/*
{
    "min": 2,
    "max": 1000,
    "o": null,
    "val": "undefined",
    "re": "/^\\d+$/",
    "m": "fn"
}
*/

A single argument is passed to the toJSON method: the name of the object on which it is defined. The toJSON method can access the object on which it is defined using the this keyword. Our toJSON method demonstrates by looping through the properties of the object:

for ( var prop in this ) { ...

We define an object o inside the toJSON method and assign the property names and values we wish to pass to JSON.stringify to the new object. We assign the following when leaving values unchanged:

o[prop] = this[prop];

You can use property name or value to screen and modify the object, much like the replacer function, as shown in the example above. Our toJSON method returns o, which is passed to JSON.stringify.

Using toJSON with a Replacer or Filter

When using a toJSON method, you can also include a replacer or filter argument when calling JSON.stringify, as the following demonstrates:

var json = JSON.stringify(obj, ['min', 'max', 're', 'm'], 4);
console.log(json);
/*
{
    "min": 2,
    "max": 1000,
    "re": "/^\\d+$/",
    "m": "fn"
}
*/

Download Examples

A download file provides this tutorial's examples free of charge. Donations are appreciated!