ddn.data.ndjson

Newline-Delimited JSON (NDJSON) Reader/Writer

NDJSON (also known as JSON Lines) stores one JSON value per line. This module provides record framing, incremental reading and writing on top of the strict RFC 8259 parser and writer in ddn.data.json; it does not add a second JSON parser.

Framing rules:

  • Records are separated by LF (\n); a trailing CR (\r) before the

    LF is removed, so CRLF input is accepted.

  • The last record does not need a terminating LF.
  • Lines that contain only spaces, tabs or CR are blank. They are

    skipped by default; with NdjsonPolicy.skipBlankLines == false they are yielded and therefore fail JSON parsing.

  • A UTF-8 byte order mark at the start of the stream is skipped when

    NdjsonPolicy.acceptUtf8BOM is set.

  • Each record may be any JSON value, not only an object.
  • A record longer than NdjsonPolicy.maxRecordLength bytes (excluding

    the LF) is an error. This bounds the memory used for a missing or corrupted newline.

Error handling is explicit: NdjsonErrorMode.FAIL_FAST (default) stops at the first malformed or oversized record, and NdjsonErrorMode.SKIP drops the record and counts it in NdjsonReadStats. Records are never dropped silently; check failed and stats after reading.

Layers:

  • NdjsonSplitter - push-based framing over caller-supplied chunks.
  • ndjsonRecords - input range of raw NdjsonRecord text slices,

    useful when a caller needs the original JSON text (for example to read exact decimal numbers with ddn.data.json.JsonLexer).

  • ndjsonValues / parseNdjson - records parsed into ddn.var.var.
  • NdjsonWriter / toNdjson - compact one-line-per-record output.

Number mapping follows ddn.data.json: integers map to long/ulong, and other numbers map to double. Use ndjsonRecords and the JSON lexer when exact decimal text must be preserved.

Examples

import ddn.data.ndjson;
import ddn.var : var;

var[] values;
NdjsonReadStats stats;
assert(parseNdjson(values, "{\"a\":1}\n{\"a\":2}\n", stats));
assert(values.length == 2 && values[1]["a"].as!long == 2);

assert(toNdjson(values) == "{\"a\":1}\n{\"a\":2}\n");

// Streaming from a file without loading it into memory:
// import std.stdio : File;
// foreach (v; ndjsonValues(File("data.ndjson").byChunk(64 * 1024))) { ... }

See Also

ddn.data.json for the underlying parser and writer.

Types 11

enumNdjsonErrorCode : ubyte

Machine-readable NDJSON error categories.

NONENo error.
INVALID_JSONA record is not a valid JSON value; see `NdjsonError.json`.
RECORD_TOO_LONGA record exceeds `NdjsonPolicy.maxRecordLength`.
INVALID_RECORDA record passed to the writer contains a line break or is empty.
enumNdjsonErrorMode : ubyte

How a reader reacts to a malformed or oversized record.

FAIL_FASTStop at the first bad record; the reader reports `failed`.
SKIPDrop the bad record, count it in `NdjsonReadStats` and continue.

A non-throwing NDJSON error report.

line and offset locate the start of the offending record in the whole stream; column is the 1-based column inside that line when the JSON parser reported one.

Fields
NdjsonErrorCode codeMachine-readable error category.
string messageHuman-readable message.
size_t line1-based physical line number of the record (0 if unknown).
size_t column1-based column within the record line (0 if unknown).
size_t offset0-based byte offset of the record start in the stream.
JsonError jsonUnderlying JSON error for `NdjsonErrorCode.INVALID_JSON`.

Policy controlling NDJSON reading.

Fields
JsonPolicy jsonPolicy applied when parsing each record as JSON.
NdjsonErrorMode errorModeReaction to malformed or oversized records.
bool skipBlankLinesSkip lines that contain only spaces, tabs or CR.
size_t maxRecordLengthMaximum record length in bytes, excluding the LF; 0 means unlimited.
bool acceptUtf8BOMSkip a UTF-8 byte order mark at the start of the stream.

Counters and diagnostics collected while reading.

Fields
size_t recordsNon-blank records framed (including records that later failed to parse).
size_t valuesRecords successfully parsed into values (value readers only).
size_t blankLinesBlank lines encountered.
size_t errorsErrors encountered (skipped records in `SKIP` mode, at most 1 in `FAIL_FAST`).
NdjsonError firstErrorThe first error encountered.
NdjsonError lastErrorThe most recent error encountered.

One framed NDJSON record.

text excludes the LF terminator, a trailing CR and a leading byte order mark. It may alias the caller's input chunk or the splitter's internal buffer and is valid only until the next NdjsonSplitter.next/push call (or the next popFront of a record range).

Fields
const(char)[] textRecord text (one JSON value).
size_t line1-based physical line number.
size_t offset0-based byte offset of the record start in the stream.
enumNdjsonStreamResult : ubyte

Result of an NdjsonSplitter.next call.

NEED_MOREThe current chunk is consumed; `push` more input or call `finish`.
RECORDA record was produced.
ENDThe stream is finished and every record has been produced.
ERRORA record failed in `FAIL_FAST` mode; the splitter stays failed.

Push-based NDJSON record splitter.

Feed input with push, then call next until it returns NEED_MORE; after the last chunk call finish and drain until END. A pushed chunk is not copied unless a record spans chunk boundaries, so the chunk must stay valid and unchanged until next returns NEED_MORE, END or ERROR. Only the incomplete tail of a chunk is buffered, bounded by NdjsonPolicy.maxRecordLength.

Examples

NdjsonSplitter sp;
NdjsonRecord rec;
NdjsonError err;
sp.push("{\"a\":1}\n{\"a\"");
assert(sp.next(rec, err) == NdjsonStreamResult.RECORD);
assert(sp.next(rec, err) == NdjsonStreamResult.NEED_MORE);
sp.push(":2}");
sp.finish();
assert(sp.next(rec, err) == NdjsonStreamResult.RECORD);
assert(rec.text == "{\"a\":2}");
assert(sp.next(rec, err) == NdjsonStreamResult.END);
Methods
void push(const(char)[] chunk) @safe pure nothrowSupply the next chunk of input.
void finish() @safe pure nothrow @nogcMark the input as complete. A final record without LF is then produced.
const(NdjsonReadStats) stats() @property ref const return @safe pure nothrow @nogcReading statistics collected so far.
bool failed() @property const @safe pure nothrow @nogcWhether the splitter stopped on an error in `FAIL_FAST` mode.
NdjsonStreamResult next(out NdjsonRecord record, out NdjsonError err) @safe pure nothrowProduce the next record.
Constructors
this(NdjsonPolicy policy)Construct a splitter using `policy`.
structNdjsonRecordRange(R) if (isInputRange!R && isNdjsonChunk!(ElementType!R))

Input range of raw NDJSON records over a range of chunks.

Copies of the range share state, so failed and stats remain valid after foreach. Chunks are consumed lazily: the source is advanced only when the splitter needs more input, so chunk buffers reused by the source (such as File.byChunk) remain valid for the current record. front.text is valid until the next popFront.

Methods
bool empty() @property constWhether all records have been produced or reading failed.
NdjsonRecord front() @property constThe current record.
void popFront()Advance to the next record.
bool failed() @property constWhether reading stopped on an error in `FAIL_FAST` mode.
NdjsonError error() @property constThe error that stopped reading.
NdjsonReadStats stats() @property constReading statistics.
Constructors
this(R source, NdjsonPolicy policy)Construct a range over `source`.
Nested Templates
State
structNdjsonValueRange(R) if (isInputRange!R && isNdjsonChunk!(ElementType!R))

Input range of NDJSON records parsed into var values.

Copies of the range share state. In FAIL_FAST mode the range ends at the first malformed record and failed is set; in SKIP mode malformed records are counted in stats and skipped. Parsed values own their data and remain valid after popFront.

Methods
bool empty() @property constWhether all values have been produced or reading failed.
var front() @propertyThe current value.
void popFront()Advance to the next value.
size_t line() @property const1-based line number of the current value.
size_t offset() @property constStream byte offset of the current value.
bool failed() @property constWhether reading stopped on an error in `FAIL_FAST` mode.
NdjsonError error() @property constThe error that stopped reading.
NdjsonReadStats stats() @property constReading statistics.
Constructors
this(R source, NdjsonPolicy policy)Construct a value range over `source`.
Nested Templates
State
structNdjsonWriter(Sink) if (isOutputRange!(Sink, char))

Writes NDJSON records to an output range of char.

Each value is written as compact JSON followed by LF; pretty printing is always disabled so that one record occupies exactly one line. The writer is itself an output range of var.

Examples

import std.array : appender;

auto w = ndjsonWriter(appender!string());
w.put(var(1));
NdjsonError err;
assert(w.putRaw(`{"exact":1.10}`, err));
assert(w.sink.data == "1\n{\"exact\":1.10}\n");
Methods
void put(const var value)Write one value as a record.
bool putRaw(const(char)[] json, out NdjsonError err, JsonPolicy policy = JsonPolicy.init)Write pre-serialised JSON text as a record after validating it.
size_t records() @property constNumber of records written.
Sink sink() @property ref returnThe destination output range.
Constructors
this(Sink sink, JsonWriteOptions opts = JsonWriteOptions.init)Construct a writer.

Functions 7

fnauto ndjsonRecords(R)(R chunks, NdjsonPolicy policy = NdjsonPolicy.init) if (isInputRange!R && isNdjsonChunk!(ElementType!R))Iterate raw NDJSON records from a range of chunks.
fnauto ndjsonRecords(const(char)[] text, NdjsonPolicy policy = NdjsonPolicy.init)Iterate raw NDJSON records from in-memory text without copying.
fnauto ndjsonValues(R)(R chunks, NdjsonPolicy policy = NdjsonPolicy.init) if (isInputRange!R && isNdjsonChunk!(ElementType!R))Iterate NDJSON values from a range of chunks.
fnauto ndjsonValues(const(char)[] text, NdjsonPolicy policy = NdjsonPolicy.init)Iterate NDJSON values from in-memory text.
fnbool parseNdjson(out var[] values, const(char)[] input, out NdjsonReadStats stats, NdjsonPolicy policy = NdjsonPolicy.init) @safeParse complete NDJSON text into values.
fnauto ndjsonWriter(Sink)(Sink sink, JsonWriteOptions opts = JsonWriteOptions.init) if (isOutputRange!(Sink, char))Create an `NdjsonWriter` for `sink`.
fnstring toNdjson(const(var)[] values, JsonWriteOptions opts = JsonWriteOptions.init) @safeSerialise values as NDJSON text.

Variables 2

enumvarNDJSON_DEFAULT_MAX_RECORD_LENGTH = 64 * 1024 * 1024

Default upper bound for a single record, in bytes (64 MiB).

enumvarisNdjsonChunk = is(T : const(char)[]) || is(T : const(ubyte)[])

True when T can be used as an NDJSON input chunk (char or ubyte arrays, as produced by strings or std.stdio.File.byChunk).