Using a Replacer or Filter with JSON.stringify

Earlier we demonstrated and described the use of JavaScript's JSON.stringify method. On this page we continue the discussion by showing how a replacer or filter can be used with JSON.stringify to screen or modify results.

JSON.stringify has an optional second argument: a replacer or filter that can be a function or an array. If it is an array, it specifies by name which entries to include in the stringify result. If it is a function, it can be used to eliminate entries or change their values. As with the stringify method itself, the results of the filter or replacer differ depending upon whether you are applying it to an object or an array.

For our discussion we will refer to the array form of the second argument as a filter and the function as replacer. We will demonstrate both with objects and arrays. We will start with filter since it is simpler. The replacer function is described and demonstrated below.

Using a Filter Array with JSON.stringify

First we demonstrate applying a filter array to a JavaScript object. We use an array as the second argument to specify that the today property, the obj property and it's min, max, and re properties should be included in the results of stringify:

var myObject = {
    num: 50,
    str: 'A string here',
    today: new Date(),
    ar: ['one', 'two', 'three'],
    obj: {
        min: 2,
        max: 1000,
        bool: true,
        o: null,
        val: undefined,
        re: /^\d+$/,
        fn: function(val) {
            // code here
        }
    }
}

var json = JSON.stringify(myObject, ['today', 'obj', 'min', 'max', 're'] );
console.log(json);
// {"today":"2015-02-03T16:24:56.935Z","obj":{"min":2,"max":1000,"re":{}}}

The output of console.log (displayed in code comments) confirms that these properties have been preserved in the stringify result. Note: if we had included the 'fn' or 'val' properties in our filter array, they would still not have been included in the result since they contain data types not supported by JSON.

Applying a Filter to an Array Passed to JSON.stringify

Next we try applying a filter to an array passed to JSON.stringify. Our filter specifies that the first and third entries in the array should be included in the results of stringify:

var ar = ['apple', 'orange', 'banana', 'strawberry'];

var json = JSON.stringify(ar, [0, 2] );
console.log(json);
// ["apple","orange","banana","strawberry"]

The output of console.log indicates that our filter has been ignored and that the entire array is included in the stringify result.[1]

Using a Replacer Function with JSON.stringify

Next we will explore how a replacer function can be used as the second argument to JSON.stringify to screen and modify the results.

A replacer function accepts two arguments: name and value. The name and value of each object property or array element is passed to the replacer function in turn.[2] The replacer function can use the name or value as a means of modifying the property value or removing it from the result. The value returned by the replacer function replaces the original value in the stringify result. If you return undefined the property will be removed. If you return the existing value it will be included in the result unchanged.

In our example replacer function below we examine the value (val) to see if it is a regular expression. If so, we use its built-in toString method to convert it to a string which we then return. We examine the name passed, and if it is str, we return undefined to remove that entry from the stringify result. If name and value do not match either of these checks, the existing value is returned unchanged in our example.

var myObject = {
    num: 50,
    str: 'A string here',
    today: new Date(),
    ar: ['one', 'two', 'three'],
    obj: {
        min: 2,
        max: 1000,
        bool: true,
        o: null,
        val: undefined,
        re: /^\d+$/,
        fn: function(val) {
            // code here
        }
    }
}

// example replacer function
function replacer(name, val) {
    // convert RegExp to string
    if ( val && val.constructor === RegExp ) {
        return val.toString();
    } else if ( name === 'str' ) { // 
        return undefined; // remove from result
    } else {
        return val; // return as is
    }
};

// passing replacer and indent to stringify
var json = JSON.stringify(myObject, replacer, 4);
console.log(json);
/*
{
    "num": 50,
    "today": "2015-02-03T17:00:56.914Z",
    "ar": [
        "one",
        "two",
        "three"
    ],
    "obj": {
        "min": 2,
        "max": 1000,
        "bool": true,
        "o": null,
        "re": "/^\\d+$/"
    }
}
*/

We included the third optional argument in this example to introduce white space into the result for easier reading. Notice the fn and val properties are not included in the result since their values are unsupported data types in JSON.

Applying a Replacer Function to an Array

Next we try applying a relacer function to an array passed to JSON.stringify.

var ar = ['one', 'two', 'three'];

function replacer2(i, val) {
    if ( i === '0' ) { // identity operator and index in quotes
        return undefined; // attempt to remove from result
    } else if ( i == 1 ) { // equality operator and numeric version of index
        return 2;
    } else {
        return val; // return unchanged
    }
}

var json = JSON.stringify(ar, replacer2);
console.log(json);
// [null,2,"three"]

We attempt to remove the first entry by returning undefined. Notice that we use the identity operator (===) and the quoted string for its index ('0').[3] However, the stringify result indicates the value was changed to null but the element was not removed. We were successful in changing the second element's value from 'two' to 2.

In short, a replacer function can't be used to remove elements from an array but can be used to modify their values.

Using a toJSON Method with JSON.stringify

Find out about the toJSON method and how you can use it to control the results of JSON.stringify.

Download Examples

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

Back to top


  1. References on JSON.stringify at MDN and MSDN verify that array filters will not be applied to arrays. ^
  2. If an array is being stringified, name (i.e., the first argument) is the index value of the array element in quotes. If a primitive value is passed to stringify, name is an empty string. ^
  3. When the replacer function is called the first time, an empty string is passed for the first argument. (See MDN on replacer.) This would match i == 0. For index values other than zero, it is okay to use the equality operator and the numeric index value due to JavaScript's data type conversion. ^