Skip to content

JSON stringify replacer function | Example code

  • by

The JSON stringify() method has an optional parameter replacer function in JavaScript. Either a function or an array is used to transform the result. The replacer is called for each item.

If replacer is null or not provided, all properties of the object are included in the resulting JSON string.

function replacer(key, value) {
  // Modify the value or return undefined to exclude the property
  return modifiedValue;
}

The replacer function can be used to selectively include, exclude, or modify values during the serialization.

JSON stringify replacer

Simple example code Using the replacer function to replace the value of “city” to upper case.

<!DOCTYPE html>
<html>
<body>

  <script>

    var obj = {name: "Martin", age: 30, city: "United States"};
    console.log(obj);

    var text = JSON.stringify(obj, function (key, value) {
      if (key == "city") {
        return value.toUpperCase();
      } else {
        return value;
      }
    });

    console.log(text)
  </script>

</body>
</html> 

Output:

JSON stringify replacer function

Applying a Replacer Function to an Array

Remove the first entry by returning undefined and changing the second element’s value from 'two' to 2.

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

function replacer2(i, val) {
    if ( i === '0' ) { 
        return undefined; 
    } else if ( i == 1 ) { 
        return 2;
    } else {
        return val; 
    }
}

var json = JSON.stringify(ar, replacer2);
console.log(json);

Output: [null,2,”three”]

replacer function Example

Let us explore how to convert a function to a string in order to keep it in the stringified object:

const user = {
      name: 'Danielle',
      age: 24,
      city: 'Seattle',
      admin: false,
      greet: function greet() {
        return 'Hello World!'
      }
    };
    function replacer(key, value) {
      if (typeof value === 'function') {
        return value.toString()
      }
      return value
    }
const userStringified = JSON.stringify(user, replacer, 3);
console.log(userStringified);

Output:

{
   "name": "Danielle",
   "age": 24,
   "city": "Seattle",
   "admin": false,
   "greet": "function greet() {\n        return 'Hello World!'\n      }"
}

Do comment if you have any doubts or suggestions on this JS JSON topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading