Mansi
Mansi

Reputation: 35

In JavaScript, how will you change the default output of JSON.stringify for any object

How will you change the default output of JSON.stringify for any object.

Upvotes: 0

Views: 61

Answers (1)

wholevinski
wholevinski

Reputation: 3828

You can provide a "replacer" function with special logic for your object type. Check out the docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter

An example from their docs:

function replacer(key, value) {
  if (typeof value === "string") {
    return undefined;
  }
  return value;
}

var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
var jsonString = JSON.stringify(foo, replacer);

Upvotes: 1

Related Questions