CBOR - JSON Encoding

12/12/2021, Sun
Categories: #JavaScript
Tags: #NodeJs

Compact Binary Format for JSON Data Transfer

When you wish to use JSON for its convenience, but also want to send the JSON using a more compact representation to save data that needs to be transfer, you will need to use an information encoder for JSON. These encoders tend to represent the JSON data in binary format for transfer and there are many out there.

While other encoders out there are general purpose, there are encoders which focus on encoding JSON, but we will pick CBOR as an example.

CBOR is a binary data serialization format which can process a JSON object by encoding for transferring and decoding for reading. Not only is the data representation smaller, the serializing and deserializing is also faster than the native JSON functions.

Here is how it can be used in the cbor-x npm package:

import { decode, encode } from 'cbor-x';

// On the client
let serializedAsBuffer = encode(value);

// Send serializedAsBuffer over to the server

// On the server
let data = decode(serializedAsBuffer);