Showing revision 16

jdai

JData Interface

A fast, portable C++11 library and Python/MATLAB/Octave toolbox for JSON, BJData, UBJSON and MessagePack, with JData annotations decoded and encoded on the way: N-D arrays, compression, N-D tiles and direct access to the members of a file.

C++11, no dependencies8 built-in codecs multi-threadedN-D tilesJSON-Mmap direct access BSD-3 / GPL-3
PythonMATLAB GNU OctaveC++11 C99command line
4-600×faster jsonlab loadjson/loadbj/savejson/savebj
4.3 msto update one record of a 25 MB document in place (JSON or MessagePack: 259+ ms)
0.03 msto read one member of a 268 MB .pmat file (full load: 53 ms)
1.5-5.5×faster region reads of a tiled volume than Blosc2 and HDF5 (2-11× with zlib)

Why jdai

jdaithe other formatshorter is better

vs Arrow IPC

  • Updates one array in place (Arrow writes the whole file again)
    update one array, ms
    jdai114 ms
    Arrow IPC310-367 ms
  • Compresses numbers (byte shuffle; Arrow IPC has none)
    256 MiB of noisy doubles, MB
    jdai194 MB
    Arrow zstd253 MB
  • Smaller tables (enumerations and shuffled columns)
    1M rows, MB
    jdai5.7 MB
    Arrow zstd10.9 MB
  • Any document: N-D and complex arrays, nested objects and tables in one file, not only columns

Arrow loads faster: compressed arrays in 78 ms against 111-146 (Arrow zstd, 253 MB against 194), raw arrays a little faster than jdai's views (48-60 ms against 63; its lz4 file is stored raw), and a table to numpy in 81 ms against 162.

vs HDF5

  • Loads compressed arrays 2× faster
    256 MiB of doubles (HDF5 with Blosc2), load ms
    jdai119 ms
    HDF5256 ms
    file size, MB
    jdai194 MB
    HDF5197 MB
  • Tables
    1M rows (HDF5 with Blosc2), MB
    jdai5.7 MB
    HDF593 MB
    load, ms
    jdai162 ms
    HDF51396 ms
  • Tiled volumes: slices, lines and blocks read 1.5-5.5× faster with the same tiles and codec (2-11× with zlib)
  • No HDF5 library: plain JSON or BJData underneath, readable by any parser; nested lists and objects too (one record of a 25 MB document in 1.9 ms)

HDF5 updates one compressed array faster (34-53 ms against 114), and is faster on complex arrays (8 ms against 16 to read one) and on one of many small arrays (0.8 ms against 1.3).

vs Parquet

  • Smaller tables
    1M rows, MB
    jdai5.7 MB
    Parquet zstd8.5 MB
  • Changes in place (Parquet writes the whole file again)
    update one array, ms
    jdai114 ms
    Parquet zstd619 ms
  • N-D arrays (with their shapes, not flattened columns)
    256 MiB of doubles, MB
    jdai194 MB
    Parquet zstd204 MB
    load, ms
    jdai111 ms
    Parquet zstd113 ms
  • Any document: complex numbers, nested objects and lists, not only tables

Parquet converts a table to numpy faster (111 ms against 162); its compressed arrays load about as fast as jdai's (113 ms against 111-119).

vs JSON

  • One record from a 25 MB document
    read, ms
    jdai1.9 ms
    msgspec213-231 ms
  • Updates in place (against parsing and writing it again)
    update, ms
    jdai4.3 ms
    msgspec259-284 ms
  • Binary arrays (no number-to-text conversion)
    one 32 MiB array of 256 MiB, ms
    jdai8.3 ms
    orjson5.2 s
  • The same data model: plus typed N-D arrays, compression and tables; .jmat files are valid JSON

orjson and msgspec save a whole document 2-3× faster (38-55 ms against 112) and load it faster (183-202 ms against 244).

Measured on the same machine with each format at its best (see Performance); the grey line under each card is where the other format still wins. jdai here: zlib (its most portable codec) or zstd with byte shuffle; the others with their best settings (HDF5 in 4 MiB chunks, Arrow in one batch, Parquet with byte_stream_split).

One library, every language

The work is done once, in C++ with up to 8 threads; each language gets a native interface: numpy arrays in Python, structs and arrays in MATLAB/Octave (through jsonlab), a nlohmann/json-style neurojson::jdata class in C++, a JData struct of functions in C, and the jdaiconv tool.

import numpy as np
import jdai

obj = {"name": "scan", "image": np.zeros((256, 256, 64), np.uint16), "tags": ["a", "b"]}

jdai.save(obj, "scan.bjd", compression="zstd")   # format from the file name
back = jdai.load("scan.bjd")                     # numpy arrays keep their dtype and shape

b = jdai.dumps(obj)                              # BJData bytes
t = jdai.dumps(obj, format="json", indent=2)     # JSON text (arrays as JData annotations)
obj = jdai.loads(b)
% jsonlab uses the jdai MEX file by itself once it is on the path
addpath('/path/to/jsonlab');
addpath('/path/to/jdai/bindings/matlab');

data = loadbj('scan.bjd');                       % 4-600x faster than the .m code
savejson('', data, 'FileName', 'scan.json', 'Compression', 'zlib');

% or call it directly
[data, needdecode] = jdai('loadbj', 'scan.bjd', struct());
bytes = jdai('savebj', '', data, struct('Compression', 'zstd'));
jdai('threads', 4);
#include "jdai/jdai.hpp"
using neurojson::jdata;

jdata j = {
    {"name", "scan"},
    {"tags", {"a", "b"}},                                   // a list
    {"affine", neurojson::matrix({{1., 0.}, {0., 1.}})},    // a typed 2x2 double array
    {"img", neurojson::zeros<float>({181, 217, 181})},      // a typed N-D array
};
j["meta"]["subject"] = "s01";                               // nlohmann/json-style
auto img = j["img"].nd<float>();                            // a typed view: img(i, j, k)
img(90, 108, 90) = 1.0f;

std::string text = j.dump(2);                               // JSON
std::vector<std::uint8_t> bytes = jdata::to_bjdata(j);      // BJData (also msgpack, ubjson)
j.save("scan.pmat");                                        // format from the file name
#include "jdai/jdai.h"

double affine[4][4] = {{1, 0, 0, -90}, {0, 1, 0, -126}, {0, 0, 1, -72}, {0, 0, 0, 1}};

jdai_value* doc = JData.object();
JData.set(doc, "name", JData.string("scan"));
JData.set(doc, "affine", JData.matrix(JDAI_DOUBLE, 4, 4, affine));

jdai_save_options o = JData.options();
o.compression = "zstd";
JData.save_with("scan.pmat", doc, &o);

jdai_value* back = JData.load("scan.pmat");
printf("%s\n", JData.as_string(JData.get(back, "name"), NULL));
JData.release(back);
JData.release(doc);
jdaiconv data.json data.bjd                      # JSON to BJData
jdaiconv -z zstd -s data.bjd data.jdt            # to JSON, zstd-compressed shuffled arrays
jdaiconv -z zlib --chunks auto vol.bnii vol.pmat # N-D tiles
jdaiconv -p data.bjd                             # a summary of the structure
jdaiconv -v data.bjd                             # only check that it parses

Format

jdai reads and writes JSON and the binary JSON formats as their specifications say, and is checked against them, and against jsonlab, on every commit. On top of them, JData annotations give N-D arrays, compression and tables, and a JSON-Mmap table gives direct access: every file stays a valid JSON or BJData document.

JSON

RFC 8259, exact locale-independent number conversion, the shortest text that reads back the same double.

BJData & UBJSON

BJData Draft 4: typed N-D arrays, structure-of-arrays containers, the extension type; UBJSON and MessagePack too.

JData annotations

JData N-D arrays of any type and memory order, complex, sparse, compressed and chunked arrays, enumerations, files of several roots.

8 codecs built in

zlib, gzip, zstd, lz4, lz4hc, lzma, lzip, xz, plus base64; block-parallel zlib (still a standard stream) and byte shuffling.

N-D tiles

chunks="auto" compresses arrays in tiles of 256 KiB-1 MiB, so a slice, a line or a block is read, or written back, by decoding only the tiles it meets.

JSON-Mmap

.pmat/.jmat files carry a JSON-Mmap table: one member is read or updated in place without parsing the rest.

Inside the format

JData stores what JSON cannot - N-D arrays, complex and sparse arrays, compressed payloads - as JSON objects with reserved names, so the document stays valid JSON (or BJData) for every parser:

  • _ArrayType_ (int8 to uint64, half, single, double, logical) and _ArraySize_, the shape;
  • _ArrayData_, the values in row-major order (_ArrayOrder_ for column-major), or compressed: _ArrayZipType_, _ArrayZipSize_, _ArrayZipData_;
  • _ArrayIsComplex_, _ArrayIsSparse_, _ArrayShuffle_, _ArrayChunks_.

jdai decodes them on the way in, into numpy arrays, MATLAB arrays or neurojson::jdata typed arrays, and chooses them on the way out. In BJData, an uncompressed array needs no annotation at all: a typed N-D array ([$d#[$U#U2 ...) holds its raw bytes.

{"_ArrayType_": "single", "_ArraySize_": [181, 217, 181],
 "_ArrayZipType_": "zstd", "_ArrayShuffle_": 4,
 "_ArrayZipSize_": [1, 7109137], "_ArrayZipData_": "KLUv/WBQ..."}

→ a 181 × 217 × 181 float32 volume

A list of records with the same keys - a table - is stored in BJData as a structure of arrays (Draft 4): a schema names each field and its type once, then the values follow column by column ({$, the default) or record by record ([$).

  • numbers at their own width: an integer column takes the smallest type that holds all its values;
  • text as a dictionary when few values repeat, as fixed-length strings, or with an offset table;
  • booleans, fixed-length vectors and nested records too.

In any format, a list of 16 or more strings with at most half as many distinct ones becomes a JData enumeration. Together: a 1-million-row table in 5.7 MB, against Parquet's 10.0 MB; read back as records, or as numpy columns (load(..., soa="columns")).

a list of records {id:1, x:0.5, g:"a"}{id:2, x:1.0, g:"b"}{id:3, x:1.5, g:"a"} BJData: schema once, then columns {$ {id:U x:D g:dict} #3 id1 2 3x.5 1 1.5 g: a,b1 2 1 enumeration (any format) ["M","F","M","M",...] → {"_EnumKey_": ["M","F"], "_EnumValue_": [1,2,1,1,...]} codes: smallest unsigned type, 0 for null; compressed as any array

chunks= cuts a compressed array into N-D tiles (_ArrayChunks_, the tile shape), each compressed on its own, on its own thread.

  • "auto": tiles of about 256 KiB (arrays up to 64 MiB) or 1 MiB (larger ones), for arrays of 2 or more dimensions and at least 2 MiB;
  • load_region decodes only the tiles a slice, line or block meets;
  • with {"index": True, "slack": 16}, an _ArrayChunkIndex_ gives each tile's byte offset, and spare bytes after each tile let update_region write a changed tile back in place;
  • a tile of one value can be stored as that number.

On the colin27 atlas in 32³ tiles: a slice in 0.69 ms, a voxel in 0.1 ms, against 6.9 ms for any read of the same volume in one payload.

a 2-D view of an array in 6 × 4 tiles a line: 6 of 24 tiles decoded a block: 1 tile "_ArrayChunks_": [32, 32, 32], "_ArrayChunkIndex_": [...] each tile compressed on its own thread; slack after each for in-place rewrites
codecfor
zstdsmall files, fast to decode: the recommended default
lz4, lz4hcthe fastest saves and loads, 5-10% larger
zlib, gzipevery reader: jsonlab without zmat, Python's standard library; block-parallel
lzma, xz, lzipthe smallest files, slowly

Byte shuffling (shuffle=True, _ArrayShuffle_) regroups the bytes of each number by position before compressing: 256 MiB of noisy doubles take 194 MB instead of 253 MB. Arrays of up to 300 elements are left uncompressed (compress_min), where a codec would cost more than it saves. All the codecs are built in: jdai's own DEFLATE and Zstandard, and the bundled LZ4 and LZMA SDK.

three float32 numbers, 4 bytes each a0a1a2a3b0b1b2b3c0c1c2c3 byte-shuffled (_ArrayShuffle_: 4): bytes grouped by position a0b0c0a1b1c1a2b2c2a3b3c3 signs and exponents of nearby numbers line up: long runs the codec compresses

zlib is the codec every reader has, but a zlib stream is normally inflated by one thread. jdai writes the zlibmt layout of zmat and pyjdata:

  • the payload is cut into blocks (a 16th of it, 256 KiB to 4 MiB), deflated independently on up to 8 threads;
  • each block ends in a full flush, the empty stored block 00 00 ff ff, so the concatenation is one standard zlib or gzip stream, with its Adler-32 computed in parallel too;
  • reading, jdai inflates the segments between those marks speculatively on all threads, and keeps one only when the inflate before it is proven to end exactly there; anything not proven is inflated serially, so every zlib stream decodes correctly.

Within a few percent of zstd's size; with 8 threads, zlib loads as fast as single-threaded zstd or faster.

the payload, in blocks (payload/16, 256 KiB-4 MiB) block 1block 2block 3block 4 thread 1thread 2thread 3thread 4 deflated independently, each ending in a full flush 78 9c | block 1 · 00 00 ff ff | block 2 · 00 00 ff ff | ... | adler32 one standard zlib stream: any reader inflates it; jdai inflates the blocks on all threads

A .pmat (BJData) or .jmat (JSON) file starts with a JSON-Mmap table, then the document. The table gives the byte locators [path, [start, length, before, after]] of the document, each top-level member and each large payload, so:

  • load(..., keys=...) parses only those bytes: one member of a 268 MB file in 0.03 ms, against 53 ms for all of it;
  • update rewrites a member in place when it fits its old bytes and the padding around them; locator numbers have a fixed width, so the table is rewritten without moving the document;
  • a value that grew is appended after the document as a JData replacement record, its old place holding a _DataReplace_ stub; load puts it back, and repack compacts the file, as h5repack does.

It is still a plain JSON or BJData file: the table is its first root. The table of a small file jdai wrote:

a .pmat file: [table]{document}, then any moved values table { meta | n | image: payload ......... } moved one member or payload is read, or rewritten, alone
[["MmapVersion", "0.5"], ["ReferenceFileBytes", 938419],
 ["$", [1, 938111, 0, 0]],                ← [start, length, before, after]
 ["$.meta", [8, 17, 0, 0]],
 ["$.n", [28, 2, 0, 0]],
 ["$.image._ArrayZipData_", [172, 937938, 0, 0]],
 ["$.image", [37, 938074, 0, 0]]]
File namesFormatTypical use
.json .jdt .jnii .jmsh .jbidsJSON (arrays as JData annotations)text people read and edit; any JSON tool
.bjd .jdb .bnii .bmsh .jbatBJDatacompact binary, typed N-D arrays
.pmat / .jmatBJData / JSON with a JSON-Mmap tablelarge workspaces: read or update single members
.ubj, .msgpack .mpkUBJSON, MessagePackexchange with other binary-JSON tools

Performance

Every format with everything it has: jdai's .pmat/.jmat files with their JSON-Mmap tables, views and 8-thread codecs; numpy .npz; HDF5 through h5py with gzip, zstd, lz4 and Blosc2; Arrow IPC (memory-mapped) and Parquet through pyarrow; MessagePack (msgpack, ormsgpack, msgspec); JSON (orjson, msgspec, pysimdjson, the json module); Blosc2 itself (a DictStore of NDArrays); and the bjdata C extension. Each is set up as its users would: HDF5 compressed in chunks of about 4 MiB, Arrow in one record batch (zero-copy columns), Parquet with byte_stream_split for floats (its byte shuffle), Blosc2 and HDF5's Blosc2 on 8 threads with shuffle. Compressed and uncompressed storage are ranked apart (a codec whose file is not at least 2% smaller than the format's uncompressed file, because it stored the data raw or could not shrink it, is ranked with the uncompressed and marked no size saving); jdai zlib is jdai with its most portable codec, a standard zlib stream every JData reader decodes (jdai's default is no compression). Milliseconds; shorter is faster.

Workload
Operation

compressed every codec, fastest first

uncompressed raw binary and text, fastest first

Operation
Storage

jdai zlib is jdai with its most portable codec, block-parallel zlib (with or without byte shuffle): a standard zlib stream any JData reader (jsonlab, pyjdata, JSONLab.js) decodes; jdai's default is no compression; jdai is jdai's fastest otherwise: no codec, lz4 or zstd (readers then need those codecs). Each cell: the fastest engine of that format for the operation, and how it compares with jdai's fastest (▲ slower than jdai, ▼ faster). The bar on a cell's left marks the fastest format of the row; whole file: the format has no partial read or in-place update.

The colin27 atlas (181 × 217 × 181 float32), every format in the same 32³ tiles: jdai, Blosc2 NDim, HDF5 and HDF5 with the Blosc2 filter. jdai reads the whole volume and every region 1.5 to 5.5 times faster than the others with the same codec (zstd, lz4), and 2 to 11 times faster with zlib, the most portable codec (jdai's block-parallel zlib against Blosc2's zlib and HDF5's gzip), which it also writes 10 times faster. HDF5 updates a block or a voxel about as fast as jdai, and Blosc2 is the smallest (12.4 MB against 13.2-14.2).
The jdai module against pyjdata (the jdata module: Python, numpy and the bjdata C extension), the same data and zlib compression as the MATLAB/Octave comparison: 3-9 times faster on a 2048 × 2048 array, 19-23 times on 1000 small arrays. pyjdata's zlib files are about 7% smaller (one zlib stream against jdai's blocks, which decode in parallel). AMD Ryzen 9 5900X, best of 3.
jsonlab with the jdai MEX file, against jsonlab's own .m code (MATLAB R2019b, zlib): 4-11 times faster on big arrays, up to 60 times on many small values; Octave gains up to 600 times.
neurojson::jdata against nlohmann/json 3.11.3 (one thread). A lookup index makes member access in large objects fast, typed arrays avoid one value per number, and BJData I/O is 4-70 times faster.

jdai 0.1.1 with the load-path fixes of the coming 0.1.2 (huge-page buffers, faster zstd and lz4 decoding), Python 3.10 on an AMD Ryzen Threadripper 3990X (64 cores, 251 GB), 8 threads for every library that has them, files in /dev/shm, best of 3 runs. "Load all" and "read one" sum the arrays they return, so lazily mapped data is read too. The 3-D volume ran on an AMD Ryzen 9 5900X (best of 7). Run it yourself: sh bench/compare.sh --full; the CI runs the comparison on every commit.

Sample code

More complete programs are in examples/: hello_jdai.py, arrays.py, tables.py, hello_jdata.cpp, arrays.cpp, user_types.cpp and hello_jdata.c.

Numeric arrays of any type and order; zlib, gzip, zstd, lz4, lz4hc, lzma, lzip, xz codecs.

import numpy as np, jdai

vol = np.random.rand(181, 217, 181).astype(np.float32)

# the recommended default: zstd, byte-shuffled, N-D tiles of 256 KiB-1 MiB
jdai.save({"vol": vol, "voxelsize": [1, 1, 1]}, "vol.pmat",
          compression="zstd", shuffle=True, chunks="auto")

back = jdai.load("vol.pmat")["vol"]                   # decoded on all threads
jdai.load("raw.pmat", view=True)                     # uncompressed: zero-copy views of the file

.pmat/.jmat files carry a JSON-Mmap table: one member is read or updated without parsing the rest.

import numpy as np, jdai

vol = np.random.rand(181, 217, 181).astype(np.float32)
jdai.save({"meta": {"subject": "s01"}, "image": vol, "n": 7}, "scan.pmat",
          compression="zstd", shuffle=True, chunks="auto")  # N-D tiles: arrays of 2 MiB or more

jdai.load("scan.pmat", keys="n")                     # 7: only those bytes are parsed
jdai.load("scan.pmat", keys="$.meta.subject")        # a JSON-Mmap path
jdai.load_region("scan.pmat", "image", (90,))        # one slice: only the tiles it meets
jdai.update("scan.pmat", "n", 8)                     # rewritten in place
block = np.zeros((32, 32, 32), np.float32)
jdai.update_region("scan.pmat", "image",             # only the tiles it meets
                   (slice(0, 32), slice(0, 32), slice(0, 32)), block)

A table's columns as arrays and lists: 1 million rows in 5.7 MB, against Parquet's 10.0 MB.

import numpy as np, jdai

n = 1000000
table = {"id": np.arange(n), "x": np.random.rand(n), "flag": np.arange(n) % 3 == 0,
         "group": ["g%02d" % (i % 20) for i in range(n)]}   # repeated strings: an enumeration

jdai.save({"table": table}, "table.pmat", compression="zstd", shuffle=True)
back = jdai.load("table.pmat")["table"]                     # numpy columns and lists back
x = jdai.load("table.pmat", keys="$.table.x")              # one column, through the file's table

A nlohmann/json-style interface that keeps JData's typed N-D arrays.

#include "jdai/jdai.hpp"
using neurojson::jdata;
using neurojson::matrix;

struct Point { double x, y; std::string label; };
JDAI_DEFINE_TYPE(Point, x, y, label)                  // your own types as records

jdata m = matrix({{1, 2.5}, {3, 4}});                 // double 2x2: promoted as numpy does
jdata c = matrix({{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}); // int32 2x2x2
std::vector<Point> pts(1000);
jdata p = pts;                                        // stored as a structure of arrays

neurojson::SaveOptions o;
o.jdata.compression = "zstd";
o.jdata.shuffle = -1;                                 // byte-shuffle by the element size
o.jdata.chunk_auto = true;                            // N-D tiles for large arrays
jdata({{"m", m}, {"c", c}, {"p", p}}).save("data.pmat", o);

MATLAB and GNU Octave; options jdai does not handle fall back to jsonlab's .m code.

% build the MEX file once (after building libjdai.a with CMake)
cd jdai/bindings/matlab
make_jdai('../../build/libjdai.a')
addpath(pwd)

% jsonlab's readers and writers now use it: same results, much faster
d = loadjson('dataset.json');                      % Backend 'auto' (the default)
savebj('', d, 'FileName', 'dataset.bjd', 'Compression', 'zstd');
d = loadbj('dataset.bjd', 'Backend', 'm');         % force the .m code
test_jdai('loadbj')                                % jdai against jsonlab, input by input
The data, the needOptionsWhat it gives
Recommended default: numeric arrays.pmat, compression="zstd", shuffle=True, chunks="auto"small files, reads on all threads, cheap slices and blocks
Readable everywherecompression="zlib"jsonlab without zmat and Python's standard library read it; block-parallel
Fastest saves and loadscompression="lz4", shuffle=True1.5-2× faster than zstd to write; files 5-10% larger
Fastest reads from RAM or a local diskno compression, .pmat, load(..., view=True)zero-copy views of the mapped file
Documents of many small values.pmat, load(..., keys=...)one member in a millisecond from a 25 MB document

Download & install

1

Python

Prebuilt wheels for Linux (x86_64, aarch64), macOS (Intel, Apple Silicon) and Windows, Python 3.9-3.13.

pip install jdai
2

C++ and C library, jdaiconv

CMake 3.10+ and a C++11 compiler (GCC 4.8+, Clang, Apple Clang, MSVC). Link jdai::jdai or jdai_static; #include "jdai/jdai.hpp" (C++) or "jdai/jdai.h" (C).

git clone https://github.com/NeuroJSON/jdai.git
cd jdai
cmake -S . -B build
cmake --build build -j
ctest --test-dir build
3

MATLAB and GNU Octave

Build the static library, then the MEX file; with jsonlab on the path, loadjson, loadbj, savejson and savebj use it by themselves.

% after: cmake -S . -B build -DJDAI_BUILD_SHARED=OFF && cmake --build build -j
cd bindings/matlab
make_jdai('../../build/libjdai.a')
addpath(pwd)
4

Source, issues and discussion

GitHub: NeuroJSON/jdai PyPI: jdai NeuroJSON forum

Specifications: JData · BJData · JSON-Mmap · related: jsonlab · pyjdata · pybj. jdai bundles LZ4, the LZMA SDK, Ryu and fast_float (BSD-2, public domain, Apache-2.0/Boost).

Edited November 29, 2026 15:03 by FangQ
Powered by Habitat