How to solve circular references and revive an object.
How to solve: Converting circular structure to JSON
Despite being used not that often, replacing allows for a simple solution to a common problem: Converting circular structures.
Consider the following example:
This example represents a circular structure because a hero has a team, and the team holds a reference to the hero.
JSON.stringify does not know how to solve this. We can solve it manually using the second argument of
JSON.stringify! This parameter is called a replacer. We can provide an array of all the attributes that we want to include.
As you can see, we get the name of our hero, as well as the name of our team, by providing the attributes name and team. Any given attribute will apply for nested objects. However, this could become quite messy for complex structures. Luckily we can also provide a function instead of an array as a replacer.
This implementation is making use of the simple fact that any undefined value gets omitted from the JSON string. The replacer function receives the key, as well as the value for its arguments. You can create sophisticated filters with this technique.
Make an Object stringify-able
Sometimes we would like to get a particular representation of our object, which might differ from its actual structure. This can be useful for complex objects, or whenever we just want to extract a few attributes. We can also avoid circular structures using this method.
The example above is working because
JSON.stringify will try to find a
toJSON-method on the object first, before falling back to the default implementation.
Reviving a stringified Object
The date object exposes several attributes, but the result of
JSON.stringify is a simple string. Even
console.log only returns a string. We also see a different implementation of the
Let us turn that string back into a date object.
We have got a date object! The reviver can be used whenever you want to restore an object with all of its functionality. Its usage is similar to the replacer that we have used to avoid circular structures.
You have learned, …
- … how to avoid circular structures when stringifying an object.
- … how to manipulate the return value of
JSON.stringifyfor your own objects, using the
- … how to restore objects using a reviver.
That’s all, folks!