recjson v1.2.1
๐ JSON-based serialization with the ability to have circular/infinitely-recursive references ๐
๐ฆ Table of Contents
- ๐ฆ Table of Contents
- ๐ Setup
- ๐ ๏ธ Usage
- ๐งโโ๏ธ๐ฎ What kind of sorcery is this?
- ๐ License
๐ Setup
pnpm i recjson
๐ ๏ธ Usage
๐ค Serialization
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}]}'
๐ฅ Deserialization/Parsing
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] } } }
๐งโโ๏ธ๐ฎ What kind of sorcery is this?
๐๐ 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.
๐ License
This project is licensed under the ๐ MIT License