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.
loadjson/loadbj/savejson/savebj.pmat file (full load: 53 ms)Kept as an Arrow table, without converting the columns, Arrow loads a table in a few ms.
HDF5 is faster on complex arrays, on reading or updating one of many small arrays (0.3 ms against 0.6-1.9), and on single-voxel updates.
Parquet is the lingua franca of data warehouses; jdai is for scientific data and documents.
.jmat files are valid JSONorjson and msgspec save a whole document from Python objects about 3× faster.
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.
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
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.
RFC 8259, exact locale-independent number conversion, the shortest text that reads back the same double.
BJData Draft 4: typed N-D arrays, structure-of-arrays containers, the extension type; UBJSON and MessagePack too.
JData N-D arrays of any type and memory order, complex, sparse, compressed and chunked arrays, enumerations, files of several roots.
zlib, gzip, zstd, lz4, lz4hc, lzma, lzip, xz, plus base64; block-parallel zlib (still a standard stream) and byte shuffling.
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.
.pmat/.jmat files carry a JSON-Mmap table: one member is read or updated in place without parsing the rest.
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 ([$).
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")).
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;{"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;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.
| codec | for |
|---|---|
zstd | small files, fast to decode: the recommended default |
lz4, lz4hc | the fastest saves and loads, 5-10% larger |
zlib, gzip | every reader: jsonlab without zmat, Python's standard library; block-parallel |
lzma, xz, lzip | the 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 254 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.
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:
00 00 ff ff, so the concatenation is
one standard zlib or gzip stream, with its Adler-32 computed in parallel too;Within a few percent of zstd's size; with 8 threads, zlib loads as fast as single-threaded zstd or faster.
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;_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:
[["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 names | Format | Typical use |
|---|---|---|
.json .jdt .jnii .jmsh .jbids | JSON (arrays as JData annotations) | text people read and edit; any JSON tool |
.bjd .jdb .bnii .bmsh .jbat | BJData | compact binary, typed N-D arrays |
.pmat / .jmat | BJData / JSON with a JSON-Mmap table | large workspaces: read or update single members |
.ubj, .msgpack .mpk | UBJSON, MessagePack | exchange with other binary-JSON tools |
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); and the bjdata C extension. Milliseconds; shorter is faster.
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.
.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.Python 3.10 on an AMD Ryzen 9 5900X, 8 threads for every library that has them, files in /dev/shm,
best of 3 runs (7 for the volume). "Load all" and "read one" sum the arrays they return, so lazily mapped data is read too.
Run it yourself: sh bench/compare.sh --full; the CI runs the comparison on every commit.
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 need | Options | What it gives |
|---|---|---|
| Recommended default: numeric arrays | .pmat, compression="zstd", shuffle=True, chunks="auto" | small files, reads on all threads, cheap slices and blocks |
| Readable everywhere | compression="zlib" | jsonlab without zmat and Python's standard library read it; block-parallel |
| Fastest saves and loads | compression="lz4", shuffle=True | 1.5-2× faster than zstd to write; files 5-10% larger |
| Fastest reads from RAM or a local disk | no 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 |
Prebuilt wheels for Linux (x86_64, aarch64), macOS (Intel, Apple Silicon) and Windows, Python 3.9-3.13.
pip install jdaijdaiconvCMake 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
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)
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).
![[Home]](upload/neurojson_banner_plain.png)