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))) { ... }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 theLF 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 == falsethey are yielded and therefore fail JSON parsing. - A UTF-8 byte order mark at the start of the stream is skipped when
NdjsonPolicy.acceptUtf8BOMis set. - Each record may be any JSON value, not only an object.
- A record longer than
NdjsonPolicy.maxRecordLengthbytes (excludingthe 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 rawNdjsonRecordtext 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 intoddn.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
See Also
ddn.data.json for the underlying parser and writer.Types 11
Machine-readable NDJSON error categories.
How a reader reacts to a malformed or oversized record.
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.
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.
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.
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).
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.Result of an NdjsonSplitter.next call.
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);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.this(NdjsonPolicy policy)Construct a splitter using `policy`.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.
void popFront()Advance to the next record.this(R source, NdjsonPolicy policy)Construct a range over `source`.StateInput 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.
void popFront()Advance to the next value.this(R source, NdjsonPolicy policy)Construct a value range over `source`.StateWrites 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");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.this(Sink sink, JsonWriteOptions opts = JsonWriteOptions.init)Construct a writer.Functions 7
auto ndjsonRecords(R)(R chunks, NdjsonPolicy policy = NdjsonPolicy.init) if (isInputRange!R && isNdjsonChunk!(ElementType!R))Iterate raw NDJSON records from a range of chunks.auto ndjsonRecords(const(char)[] text, NdjsonPolicy policy = NdjsonPolicy.init)Iterate raw NDJSON records from in-memory text without copying.auto ndjsonValues(R)(R chunks, NdjsonPolicy policy = NdjsonPolicy.init) if (isInputRange!R && isNdjsonChunk!(ElementType!R))Iterate NDJSON values from a range of chunks.auto ndjsonValues(const(char)[] text, NdjsonPolicy policy = NdjsonPolicy.init)Iterate NDJSON values from in-memory text.bool parseNdjson(out var[] values, const(char)[] input, out NdjsonReadStats stats,
NdjsonPolicy policy = NdjsonPolicy.init) @safeParse complete NDJSON text into values.auto ndjsonWriter(Sink)(Sink sink, JsonWriteOptions opts = JsonWriteOptions.init) if (isOutputRange!(Sink, char))Create an `NdjsonWriter` for `sink`.string toNdjson(const(var)[] values, JsonWriteOptions opts = JsonWriteOptions.init) @safeSerialise values as NDJSON text.Variables 2
NDJSON_DEFAULT_MAX_RECORD_LENGTH = 64 * 1024 * 1024Default upper bound for a single record, in bytes (64 MiB).
isNdjsonChunk = 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).