Skip to content

About

Implementation of ubjson as a common js module requiring only buffer.

Resources

Code of conduct

Stars

2 stars

Watchers

0 watching

Forks

 
 

Repository files navigation

bjd

bjd: a fast, dependency-free Binary JData (BJData) encoder and decoder for web browsers and Node.js

npm jsDelivr

Table of Contents

What's New

bjd 1.0.0

  • A complete rewrite in TypeScript, with no runtime dependencies (the buffer package is no longer needed). One source builds an ES module, a CommonJS module, a browser <script> file (plain and minified) and TypeScript declarations.
  • All of BJData Draft 4 and the Draft 5 preview: typed and N-D arrays (row- and column-major), structure-of-arrays records, extensions (dates, times, complex numbers, UUIDs), high-precision numbers, 64-bit integers (as BigInt beyond 2^53), big-endian (UBJSON) files, and several values in one file.
  • 8 to 50 times faster than bjd 0.3: close to JSON.parse and JSON.stringify on JSON-like data, and faster than them on arrays and records (see Performance).
  • Strict and safe: malformed input is rejected with a BJDataError that gives the byte offset, before any memory is allocated for it.
  • The same bytes as pybj for JSON-like data, and checked against pybj, jsonlab and jdai in both directions.

Introduction

Binary JData (BJData) is the binary JSON format of the NeuroJSON project, derived from UBJSON. It stores the same values as JSON (objects, arrays, strings, numbers, booleans and null), in a compact binary form that is fast to read and write, and adds what scientific data needs: numbers of a fixed type (int8 to uint64, half, single, double), strongly-typed arrays whose payload is the raw binary data, N-dimensional arrays, and tables stored as structures of arrays.

A Float32Array of 3 values, for example, is stored as the 18 bytes

[  $  d  #  U  3  <12 bytes: 0.5, 1.5, 2.5 as little-endian float32>

bjd reads such bytes into JavaScript values (a Float32Array here) and writes JavaScript values as BJData, in web pages and in Node.js. It reads the .bjd, .jdb, .bnii (binary JNIfTI), .bmsh (binary JMesh), .pmat and .jbat files written by jsonlab (MATLAB/Octave), pybj and jdai (Python, C++).

BJData stores the syntax; the meaning of annotated values (compressed arrays, complex and sparse arrays, tables, maps) is given by JData, which the companion library jda decodes on top of bjd. Compression is part of that layer: bjd reads and writes compressed payloads as bytes, and jda (de)compresses them, on several threads with its loadbjAsync and savebjAsync (zlibmt).

Installation

For Node.js and bundlers

npm install bjd

bjd runs on Node.js 12 or newer and has no dependencies. The package holds:

file for
dist/bjdata.cjs require('bjd') (CommonJS)
dist/bjdata.mjs import ... from 'bjd' (ES module, also for webpack, Vite, Rollup, esbuild)
dist/bjdata.js, dist/bjdata.min.js a <script> tag: defines the global bjdata
dist/types/ TypeScript declarations (found by TypeScript by themselves)

For a web page

No installation is needed. Load the minified build from a CDN, which defines the global bjdata:

<script src="https://cdn.jsdelivr.net/npm/bjd@1/dist/bjdata.min.js"></script>

(or https://unpkg.com/bjd@1/dist/bjdata.min.js), or import the ES module:

<script type="module">
  import * as bjd from 'https://cdn.jsdelivr.net/npm/bjd@1/dist/bjdata.mjs';
</script>

To serve it yourself, copy dist/bjdata.min.js (36 kB, 12 kB gzipped) next to your page, from the npm package or from a build of this repository (see Building and testing).

Using bjd in Node.js

const bjd = require('bjd');              // CommonJS
// import * as bjd from 'bjd';           // ES module (or: import bjd from 'bjd')
const fs = require('fs');

const doc = {
    name: 'scan 1',
    dims: [64, 64, 32],
    voxels: new Float32Array([0.5, 1.5, 2.5]),      // a typed array: written as raw float32
    id: BigInt('18446744073709551615'),              // 64-bit integers as BigInt
    valid: true,
};

const bytes = bjd.dumpb(doc);            // a Uint8Array
fs.writeFileSync('scan.bjd', bytes);

const back = bjd.loadb(fs.readFileSync('scan.bjd'));
console.log(back.name, back.voxels);     // 'scan 1' Float32Array [ 0.5, 1.5, 2.5 ]

loadb takes a Uint8Array, a Node.js Buffer, an ArrayBuffer or a DataView. dumpb always returns a Uint8Array; Buffer.from(bytes.buffer, bytes.byteOffset, bytes.length) makes a Buffer of it without a copy.

In TypeScript, the functions, the options and the classes are typed:

import { dumpb, loadb, BJDataError, DecodeOptions } from 'bjd';

const opts: DecodeOptions = { ndarray: 'nested' };
try {
    const value = loadb(bytes, opts);
} catch (e) {
    if (e instanceof BJDataError) {
        console.error(e.message, 'at byte', e.position);
    }
}

Using bjd in a web page

With the <script> tag, the functions are members of the global bjdata:

<!DOCTYPE html>
<html>
<body>
  <input type="file" id="file" accept=".bjd,.jdb,.bnii,.bmsh">
  <pre id="out"></pre>
  <script src="https://cdn.jsdelivr.net/npm/bjd@1/dist/bjdata.min.js"></script>
  <script>
    // a file the user picks
    document.getElementById('file').addEventListener('change', async (ev) => {
      const data = bjdata.loadb(await ev.target.files[0].arrayBuffer());
      document.getElementById('out').textContent = JSON.stringify(data, null, 2);
    });

    // a file from a server
    fetch('data/scan.bjd')
      .then((r) => r.arrayBuffer())
      .then((buf) => console.log(bjdata.loadb(buf)));

    // save a value as a file the user downloads
    function download(value, name) {
      const blob = new Blob([bjdata.dumpb(value)], { type: 'application/octet-stream' });
      const a = document.createElement('a');
      a.href = URL.createObjectURL(blob);
      a.download = name;
      a.click();
      URL.revokeObjectURL(a.href);
    }
  </script>
</body>
</html>

As an ES module, in a page or in an application built with a bundler:

<script type="module">
  import { loadb, dumpb } from 'https://cdn.jsdelivr.net/npm/bjd@1/dist/bjdata.mjs';

  const r = await fetch('data/scan.bjd');
  const scan = loadb(await r.arrayBuffer());
</script>
// in an application bundled by webpack, Vite, Rollup or esbuild (after npm install bjd)
import { loadb, dumpb } from 'bjd';

bjd works the same in browsers and in Node.js.

More examples

N-D arrays

Rectangular nested arrays of numbers are written as packed N-D arrays with pack: true; N-D arrays are read back as JData N-D array objects, or, with the ndarray option, in other forms:

const b = bjd.dumpb([[1, 2, 3], [4, 5, 6]], { pack: true });   // a 2x3 uint8 array: [$U#[$U#U 2 2 3 1 2 3 4 5 6

bjd.loadb(b);
// { _ArrayType_: 'uint8', _ArraySize_: [2, 3], _ArrayData_: Uint8Array [1, 2, 3, 4, 5, 6] }
bjd.loadb(b, { ndarray: 'nested' });   // [[1, 2, 3], [4, 5, 6]]
bjd.loadb(b, { ndarray: 'flat' });     // Uint8Array [1, 2, 3, 4, 5, 6]

// a 64x64x32 float32 volume, written from a JData N-D array object
const vol = { _ArrayType_: 'single', _ArraySize_: [64, 64, 32], _ArrayData_: new Float32Array(64 * 64 * 32) };
const bytes = bjd.dumpb({ vol });      // a packed 64x64x32 float32 array: a header and the raw floats

numjs NdArrays and scijs ndarrays are written as N-D arrays too, and ndarray: (data, shape, order, type) => value builds your own type when reading.

Tables as structures of arrays

An array of records with the same keys and value types is stored much more compactly as a structure of arrays (soa: 'row' for row-major records, 'col' for columns). Strings repeated often are stored once, in a dictionary:

const rows = [];
for (let i = 0; i < 100000; i++) {
    rows.push({ id: i, x: i * 0.5, label: ['gray', 'white', 'csf'][i % 3], ok: i % 2 === 0 });
}
const b = bjd.dumpb(rows, { soa: 'col' });

bjd.loadb(b);                          // the array of 100000 records again
bjd.loadb(b, { soa: 'columns' });      // { id: Uint32Array, x: Float64Array, label: [...], ok: [...] }

These 100000 records take 1.4 MB, against 3.8 MB as an array of objects. Read as columns, a column-major table is decoded about 15 times faster than as records, as numeric columns are copied in one step.

Dates, high-precision numbers and other extensions

const b = bjd.dumpb({ when: new Date('2026-01-01T00:00:00Z') }, { date: 'extension' });
const e = bjd.loadb(b).when;           // an Extension: e.type 6 (datetime_us), e.data its bytes
e.value;                               // a Date again

const big = bjd.loadb(bjd.dumpb(BigInt('123456789012345678901234567890')));
String(big);                           // '123456789012345678901234567890' (a HighPrec, [H])

Without date: 'extension', dates are written as ISO 8601 strings, as JSON.stringify does.

Several values in one file, and errors

const two = new Uint8Array([...bjd.dumpb({ a: 1 }), ...bjd.dumpb([2, 3])]);
bjd.loadbAll(two);                     // [ { a: 1 }, [ 2, 3 ] ]
bjd.decodeAt(two, 0);                  // [ { a: 1 }, 7 ]: the value and the offset after it

try {
    bjd.loadb(new Uint8Array([0x5b, 0x23, 0x55, 0xff]));   // [#U 255: a count with no data
} catch (e) {
    console.log(e.name, e.position, e.message);  // BJDataError 4 'bjdata: unexpected end of data (at byte 4)'
}

JData annotations, with jda

bjd handles the BJData syntax. The JData annotations stored with it (_ArrayZipData_ compressed arrays, complex and sparse arrays, tables, maps ...) are decoded by jda:

const jd = require('jda');
const doc = jd.loadbj(fs.readFileSync('brain.bnii'));   // jd.decode(bjd.loadb(...))

API reference

Function Returns
dumpb(value, options?) the BJData bytes of value (Uint8Array)
loadb(bytes, options?) the first top-level value
loadbAll(bytes, options?) every top-level value, in order (a JSON-Mmap .pmat file holds two)
decodeAt(bytes, offset?, options?) [value, offsetAfterIt]
encode(value, options?), decode(bytes, offset?) the bjd 0.x names: decode returns [value, offset]
nest(data, dims, order?) nested arrays of the shape dims from flat data ('C' row-major, 'F' column-major)

Classes: HighPrec (a high-precision number, [H]; String(hp), Number(hp)), Extension ([E]: type, data, value; Extension.fromDate(date), Extension.fromUUID(text)), BJDataError (position: the byte offset), and Encoder/Decoder, which the functions use.

How values are stored

JavaScript BJData written read back as
null, undefined Z null
true, false T, F boolean
integer number smallest of U u m M (non-negative) or i I l L number
other number (also NaN, ±Infinity, -0) D (or d when exact, with float32: true) number
BigInt smallest integer type; H beyond 64 bits number if exact, else BigInt
one-character ASCII string C string
string S (UTF-8) string
typed array (Float32Array, BigInt64Array, ...) [$type#n the same typed array
ArrayBuffer, DataView [$B#n (bytes) Uint8Array
{_ArrayType_, _ArraySize_, _ArrayData_} (JData N-D array) [$type#[dims] the same object (option ndarray)
numjs, scijs ndarray [$type#[dims] a JData N-D array object
array, Set [ ... ] ([$type# with pack: true) array
object, Map { ... } (keys in insertion order) object
array of records (with soa) [${schema}#n or {${schema}#n array of objects (option soa)
Date ISO 8601 string (an extension with date: 'extension') string
HighPrec H HighPrec
Extension E Extension

The integer types are chosen as pybj chooses them, so the two write the same bytes for JSON-like data. As with JSON.stringify, object members whose value is undefined or a function are left out, objects with a toJSON() method are written as its result, and circular structures are an error.

Encoder options (dumpb)

Option Default
count false write the count of every array and object (#n) instead of an end marker
pack false write arrays of numbers as typed arrays, and rectangular nested arrays of numbers as N-D arrays
float32 false write a non-integer as float32 when that is exact
soa false 'row' or 'col': write arrays of records that share their keys and value types as a structure-of-arrays; strings repeated often use a dictionary, others an offset table
soaThreshold 2 the fewest records written as a structure-of-arrays
sortKeys false sort the keys of objects
date 'string' 'extension': write a Date as a datetime_us extension
endian 'little' 'big': UBJSON/BJData Draft 1 byte order
replacer (value) => value for functions and symbols (left out by default)
maxDepth 1000 the deepest nesting allowed

Decoder options (loadb, loadbAll, decodeAt)

Option Default
ndarray 'jdata' N-D arrays as {_ArrayType_, _ArraySize_, _ArrayData_: TypedArray} (plus _ArrayOrder_: 'column' when column-major); 'nested': nested arrays; 'flat': the typed array alone; or (data, shape, order, type) => value
soa 'records' 'columns': a structure-of-arrays as an object of columns (typed arrays for numbers)
bigint 'auto' 64-bit integers as numbers when exact, else BigInt; 'always' BigInt; 'never' numbers
highprec 'object' [H] as HighPrec; 'string' or 'number'
extension (type, bytes) => value for [E] values (default: Extension objects)
copy true false: typed arrays are views into the input where its alignment allows
endian 'little' 'big' for UBJSON byte order
maxDepth 1000 the deepest nesting allowed

The value of an Extension gives the payload of a type reserved by the specification in a JavaScript form: epoch_s, epoch_us, datetime_us, epoch_ns: a Date; date: {year, month, day}; time_s: {hour, minute, second}; timedelta_us: microseconds; complex64/complex128: {re, im}; uuid: its text form.

Performance

Node.js 12, one thread, best of 7 (largebj.bjd and citm.bjd from jsonlab's tests; the records are {id, x, y, name, ok}):

loadb / dumpb bjd 0.3 decode / encode JSON.parse / JSON.stringify of the same data
citm.bjd (0.4 MB) 1.7 / 1.3 ms 24 / 17 ms 1.6 / 1.3 ms
largebj.bjd (25 MB) 72 / 63 ms 557 / 1650 ms 41 / 56 ms
200k records (8.8 MB) 33 / 27 ms 861 / 1284 ms 41 / 38 ms
the same as a structure-of-arrays (soa: 'row') 21 / 19 ms
the same, soa: 'col', read with soa: 'columns' 1.3 / 20 ms
1M numbers, pack: true (a Float64Array when read) 1.4 / 8 ms
64 MiB of float64 11 / 11 ms

What makes it fast: markers dispatched by their byte; short strings built without temporary arrays, and repeated short keys and values taken from a cache; Node's own UTF-8 routines for long strings (in browsers, those that were fastest in Chrome); structure-of-arrays records decoded and written a field at a time; typed payloads copied (or, with copy: false, viewed) in one step.

Upgrading from bjd 0.x

  • decode(bytes) still returns [value, offset]; loadb(bytes) returns the value alone.
  • encode(value) returns a Uint8Array (a Buffer before).
  • N-D arrays keep their shape ({_ArrayType_, _ArraySize_, _ArrayData_}; ndarray: 'flat' gives the flat typed array of 0.x).
  • Arrays of numbers are no longer written as typed arrays of their first value's type (which could not hold the others); use pack: true to write typed arrays.
  • 64-bit integers are numbers when they are exact (bigint: 'always' for BigInt).
  • The buffer package is no longer needed; require('bjd/bjdata.js') still works.

Building and testing

git clone https://github.com/NeuroJSON/js-bjdata.git
cd js-bjdata
npm install            # TypeScript and esbuild, to build
npm run build          # dist/: bjdata.mjs, bjdata.cjs, bjdata.js, bjdata.min.js, types/
npm test               # unit tests, with the byte examples of the specification
npm run test:interop   # against pybj (Python), both directions

The sources are in src/ (decoder.ts, encoder.ts, types.ts). test/browser.html, served over HTTP from the repository (for example with python3 -m http.server), runs the browser builds.

Contribution and Feedback

bjd is an open-source project. You can not only use it and modify it as you wish, but also contribute your changes back so that everyone else can enjoy the improvement. To contribute, download the source code from its repository:

git clone https://github.com/NeuroJSON/js-bjdata.git

or browse the github site at https://github.com/NeuroJSON/js-bjdata

Once you are satisfied with your changes, and ready to share them with others, please submit them as a "pull request" on github. The project maintainer, Dr. Qianqian Fang, will review the changes and choose to accept the patch.

We appreciate any suggestions and feedback from you. Please use the NeuroJSON forum to report any questions you may have regarding bjd:

NeuroJSON forum

Acknowledgement

bjd 1.0 has no dependencies; its encoder and decoder are its own. Versions up to 0.3.2 were derived from ubjson.js (Copyright (C) 2014 Kyle R. Zentner); no code of it remains (see NOTICE.txt).

About

Implementation of ubjson as a common js module requiring only buffer.

Resources

Code of conduct

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages