The JSON.stringify function

You know you can use JSON.stringify with an object to get the string.
Like:

The API is able to identify illegal JSON values (like functions) and discard them silently, so that the following code won’t throw any exception:

What is interesting of this behaviour is that even the new objects created using a function can be stringifyied and all their valid properties will be serialized.

Let’s see an example:

As per specifications if a toJSON method is provided, it will be called to retrieve the JSON representation for that specific object.

In this case:

The replacer function

Cool. Now let’s have a look to another feature from the specification  and namely the replacer function: this is a callback that we can use to filter the object’s keys in order to exclude or modify them before the API method JSON.stringify()  builds the final string. The callback is being called with two parameters: key and value which are respectively the key of the current JSON item and its value.

Gotcha #1

The first detail to be aware of is that the first callback’s iteration is being done passing it as key an empty string and as a value the full object itself. If we are filtering keys and forget to match against the empty string the entire process will stop and return undefined.

Let’s see a couple of examples.

The first implementation will act as a pass-through: we always return the value so all the fields can be serialized.

The second is expected to filter only the fields which have numeric values. But the API returns undefined instead.

Let’s fix it:

Gotcha #2

The second remarkable detail is that the replacer function will be called after the translation to JSON of the current key, so that we will not receive the original value but the JSON value.

Let’s see an example:

The error will never be thrown, because the value passed is a valid JSON and the object’s methods have already been purged.

An important corollary is that you can’t use instanceof against custom objects because since every value is plain JSON the type of every translated object is object.

Also in this case, the error will never be thrown: what you have in the filter function is the result of the serialization rather than the original object.

References

ECMA 262 Standard

ECMA 404 (JSON)

MDN: JSON.stringify