DEV Community

ViperT
ViperT

Posted on

SuperJSONatural -> Faster & binary serialization!

Truly one of the world faster serializer/parser in JS and within < 10 kB only!

Image description

The great advantage is its ease of use while it supports all JS TypedArrays! And this is great for canvas' imageData and so on...

It was annoying to us, JSON doesn't support parsing TypedArray such as data of canvas' imagedata... It doesn't...

import SuperJSONatural from "superjsonatural"; // In node.js
/* OR */
var SuperJSONatural = window.SuperJSONatural; // Use the minified version for browser

var data = {
    name: "Prof. Bernice Champlin Jr.",
    male: true,
    female: false,
    timestamp: Date.now(),
    items: Uint8Array.of(0, 55, 77, 65, 9, 1, 1, 1, 1, 200, 44, 22, 9, 0),
    email: "stevie.conn@luettgen.com",
    phone: 3476774277,
    description: "Et voluptatem incidunt repellat. Qui laboriosam quis accusamus optio sed. Non qui qui quasi aliquid.",
    other: {
        ANARRAY: ["lol", 99],
        prop: 992,
        str: "str",
        items: Uint32Array.of(999, 97219)
    }
};

// It will be a string when encoded, always
var encoded = SuperJSONatural().stringify(data);
var decoded = SuperJSONatural().parse(encoded);
console.log(data, encoded, decoded)

// NEW!!! It will be a Uint8Array (Like a bytes using an array buffer)
var encoded = SuperJSONatural().pack(data);
var decoded = SuperJSONatural().unpack(encoded);
console.log(data, encoded, decoded)

Enter fullscreen mode Exit fullscreen mode

Links: DEMO/BENCHMARK, NPM package

How it works?

Stringify/Parse

It will simply convert your typed array to base64 and prefix the resulting string with: "$TA_xx_B64$" where "xx" are a simple id to know to which kind of typed array the bytes encoded into base64 will be parsed.

Pack/Unpack

This one is a bit more complex, it encode everything as JSON just as usual and encode this stringified object into a Uint8Array (AKA: a bytes array or a buffer) with the first two bytes being the length of the encoded JSON after the first two bytes, ...

This is because (and yes there is a little change that occurs before stringifying the object), when it encounter a TypedArray, it stores which kind of typed array it is, and both the start and stop offset of the buffer that will contains all TypedArray's bytes concatenated. This second part is appended to the JSON encoded into bytes and that's it, we also achieve to decode it quite fast, on some realistic tests, we're as up as twice faster than CBOR-X the fastest (I think) robust engine of its kind on the web, until our hybrid model was born.

Other modules: https://www.npmjs.com/~asaitama

Oldest comments (0)