SuperJSON is released under the MIT license and the source code is available on GitHub.
The two main functions of SuperJSON are
SuperJSON.stringify which align with their JSON counterparts making SuperJSON a true drop-in replacement for JSON. Out of the box it supports primitives, arrays, plain objects, Dates, Maps, Sets, and TypedArrays with more built-ins coming.
Behind the scenes, SuperJSON replaces instances that aren’t supported natively by JSON with an object using the keys
"__sj_value" when stringifying. When parsing it looks for an object containing those keys and uses them to recreate a similar instance. Type informs what class to use for the recreation and the value is JSON safe data that can be used to recreate the instance.
A huge issue I have had with custom serializers and deserializers was that they were directly tied to the data structure. This made any change to the data structure require a change to the serializers and deserializers. To get around this, SuperJSON instead walks through the data structure looking at each instance in isolation. The walk method meant that SuperJSON doesn’t need to know anything about the data structure or what to do with nested data. Instead it just knows what to do with that specific instance.
With ES2015 introducing classes, I’ve found my codebases taking advantage of custom classes to streamline flows. While serializing with JSON was easy by using adding a
toJSON method to the custom class, deserializing has been an issue. This was why a key objective of SuperJSON was making supporting custom classes as easy as possible.
For a custom class all SuperJSON needs is the constructor, a serializer function, and a deserializer function. The serializer and deserializer can be written as part of class itself to make it easier to maintain. When registering a class with SuperJSON it will look for a public
toJSONValue method and a static public
fromJSONValue method for the serializer and deserializer respectively. The serializer only needs to return the data need to recreate the instance, the returned data will be ran through SuperJSON so there is no requirement for the data to be JSON-safe. The deserializer will receive a restored version of what was returned from the serializer and should do its best to recreate the original instance. Once you have completed the class you simply need to pass it to
SuperJSON.register and your done.
In some situations, you may not be able to update the class or want to provide custom serializers or deserializers.
SuperJSON.register accepts an object of options as the second argument that you can specify the name,
toJSONValue method, and
What’s next for SuperJSON?