zson

0.1.3 • Public • Published

ZSON

ZSON is binary-based JSON. It is similar to BSON or MessagePack; the difference from the two is that ZSON is designed to be streamable while being compact.

ZSON is licensed under the MIT License.

USAGE

Load:

var zson = require("zson");

Simple encode / decode:

var encoded = zson.encode({ hello: "world" });
var decoded = zson.decode(encoded);

Streaming encode:

function pushCb(octet) {
    ...
}
var encoder = new zson.Encoder(pushCb);
encoder.encodeArray(function () {
    encoder.encode(1);
    encoder.encode(2);
    encoder.encode(3);
    ...
});
encoder.encodeObject(function () {
    encoder.encodeKeyValue("hello", "world");
    ...
});

Streaming decode:

function getChar() {
    ...
}
var decoder = new zson.Decoder(getChar);
var data = decoder.decode();

Custom codec:

// dedupe strings in the stream
var dedupingEncoder = function () {
    var stringMap = {};
    return function (v) {
        if (typeof v === "string") {
            if (stringMap.hasOwnProperty(v)) {
                this.push(zson.CUSTOM_TAGS[0]);
                this.encode(stringMap[v]);
                return;
            } else {
                stringMap[v] = Object.keys(stringMap).length;
            }
        }
        return this.encodeCore(v);
    };
};

var dedupingDecoder = function () {
    var stringList = [];
    return function () {
        if (this.peek() === zson.CUSTOM_TAGS[0]) {
            this.shift();
            return stringList[this.decode()];
        }
        var decoded = this.decodeCore();
        if (typeof decoded === "string") {
            stringList.push(decoded);
        }
        return decoded;
    };
};

var encoded = zson.encode(src, { CUSTOM_ENCODER: dedupingEncoder });
var decoded = zson.decode(encoded, { CUSTOM_DECODER: dedupingDecoder });

Format

Tag Description
0xxxxxxx7-bit signed integer (-64 ~ +63)
10xxxxxx [byte]14-bit signed integer (-8192 ~ +8191)
110xxxxx [byte] [byte]21-bit signed integer (-1048576 ~ 1048575)
1110xxxx [byte] [byte] [byte]28-bit signed integer (-134217728 ~ 134217727)
11110000 [byte] [byte] [byte] [byte]32-bit signed integer
11110001 [byte] [byte] [byte] [byte]IEEE754 float (32-bit)
11110010 8*[byte]IEEE754 float (64-bit)
11110011null
11110100false
11110101true
11110110
11110111
11111000
11111001
11111010
11111011
extension points
11111100 n*[byte] 11111111UTF-8 string
11111101start of array
11111110start of object (repetition of value-key pairs, keys are raw UTF-8 strings terminated by 0xff)
11111111end of the current array or object

Examples

0xfc 0x68 0x65 0x6c 0x6c 0x6f 0xff                      -- "hello"
0xfd 0x01 0x7f 0x81 0x00 0xff                           -- [ 1, -1, 256 ]
0xfe 0xf5 0x63 0x6f 0x6d 0x70 0x61 0x63 0x64 0xff 0xff  -- {"compact":true}

Readme

Keywords

none

Package Sidebar

Install

npm i zson

Weekly Downloads

0

Version

0.1.3

License

MIT

Last publish

Collaborators

  • kazuho