Showing revision 1

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
194 MB256 MiB of noisy doubles (HDF5 zstd: 255 MB, Parquet: 262 MB)
0.03 msto read one member of a 268 MB .pmat file (full load: 53 ms)
1.4-4×faster region reads of a tiled volume than Blosc2 and HDF5

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

Formats & features

jdai follows the specifications it implements, and is checked against them, and against jsonlab, the reference implementation, on every commit.

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.

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

Each format used at its best: HDF5 through h5py (with hdf5plugin's codecs), Arrow IPC memory-mapped and Parquet through pyarrow, Blosc2 NDim arrays through python-blosc2. Milliseconds, lower is better (log scale).

Eight 2048 × 2048 double arrays (256 MiB). jdai makes the smallest files, reads one compressed array about as fast as any format and updates one in place; Arrow, Parquet and .npz write the whole file again to change one array.
The colin27 atlas (181 × 217 × 181 float32) in 32³ tiles. In tiles, jdai reads the whole volume and every region 1.4 to 4 times faster than Blosc2 and HDF5 with the same tile shape and codec; in one payload, any read costs a full decode.
1 million rows (int64, two float64, int32, bool, a 20-value category and a 50000-value string column). Repeated strings are stored as enumerations: 5.7 MB, against Parquet's 10.0 MB.
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.

AMD Ryzen 9 5900X, 8 threads for every library that has them, files on a RAM disk, best of 3 runs (7 for the volume); "load" includes summing the arrays, so that lazily mapped data is read too. Run the comparison yourself with sh bench/compare.sh; the CI runs it 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 0:10 by FangQ
Powered by Habitat