๐ JSON-based serialization with the ability to have circular/infinitely-recursive references ๐
pnpm i recjson
import { Serializer } from 'recjson';
const serializer = new Serializer();
const recursiveObject = {
a: 1,
b: {
c: {
d: {
backToTop: null as unknown as any,
},
},
},
};
recursiveObject.b.c.d.backToTop = recursiveObject;
const serialized = serializer.serialize(recursiveObject);
// { root: 0, obj: [ { a: 1, b: 2 }, 1, { c: 3 }, { d: 4 }, { backToTop: 0 } ] } - As a JS Object
const serializedAsString = serializer.serializeToJSON(recursiveObject);
// '{"root":0,"obj":[{"a":1,"b":2},1,{"c":3},{"d":4},{"backToTop":0}]}'
import { Deserializer } from 'recjson';
const deserializer = new Deserializer();
const serialized = { root: 0, obj: [ { a: 1, b: 2 }, 1, { c: 3 }, { d: 4 }, { backToTop: 0 } ] }; // As a JS Object
const deserialized = deserializer.parse(serialized); // { a: 1, b: { c: { d: [Circular] } } }
const deserializedAsString = parser.parseFromJSON('{"root":0,"obj":[{"a":1,"b":2},1,{"c":3},{"d":4},{"backToTop":0}]}'); // { a: 1, b: { c: { d: [Circular] } } }
๐๐ RecJSON is a JSON-based serialization format that allows for circular/infinitely-recursive references. It does this by using a special syntax for references.
๐ข๐ This syntax involves using an array of all objects, each with integer values, alongside primitives. When an object is referenced, it is replaced with the integer value of its index in the array. If it doesn't exist, it is added to the array.
๐๐ This allows for circular/infinitely-recursive references, as the object is only referenced by its index in the array, not by the object itself.
๐๐ฅ When deserializing, the array is used to replace the integer values with the actual objects.
This project is licensed under the ๐ MIT License
Generated using TypeDoc