ddn.data.json5

JSON5 support for DDN — Design and Policy

This module implements a JSON5 parser/writer and documents specification scope and type mapping between JSON5 values and ddn.var.

Mapping rules to var:

  • Objects: map to var.Type.OBJECT with string keys and var values.
  • Arrays: map to var.Type.ARRAY with elements converted to var recursively.
  • Strings: map to var.Type.STRING (both single-quoted and double-quoted forms are accepted).
  • Booleans: map to var.Type.BOOL.
  • null: map to var.Type.NULL.
  • Numbers:
  • If the numeric value is integral and fits a 64-bit signed integer, use Type.LONG.
  • Else if the numeric value is integral and non-negative and fits 64-bit unsigned, use Type.ULONG.
  • Otherwise, use Type.DOUBLE and preserve special cases: NaN, Infinity, -Infinity, -0.0.

Writer rules (summary):

  • Keys are unquoted when they are valid JSON5 identifiers; otherwise quoted with minimal escaping.
  • Values are emitted compactly by default; pretty printing is configurable.
  • Deterministic output is achieved by lexicographically sorting object keys by default.

Feature coverage (JSON5):

  • Comments: `//` line and C-style block comments.
  • Trailing commas in arrays/objects.
  • Unquoted keys when identifier-compatible.
  • Single-quoted strings and escape sequences, including line continuations.
  • Numbers with leading `+`, hex (0x...), leading/trailing decimal points, exponents, and special numbers.
  • BOM (UTF‑8) accepted at the beginning of input.

    Examples

    import ddn.data.json5 : parseJSON5, toJSON5, toJSON, minify, Json5Error;
    import ddn.var : var;
    
    Json5Error err;
    var v;
    assert(parseJSON5(v, "{a:1, b:'x',}", err));
    assert(v["a"].as!long == 1);
    
    // Minify JSON5 (strip comments/whitespace).
    // Note: avoid block-comment markers in DDoc examples (they can terminate DDoc blocks).
    auto compact = minify("{ a: 1, //c\n b: 2, }");
    assert(compact == "{a:1,b:2,}");
    
    // Write JSON5 vs strict JSON.
    auto json5Text = toJSON5(v);        // e.g. "{a:1,b:'x'}"
    auto jsonText  = toJSON(v);         // e.g. "{\"a\":1,\"b\":\"x\"}"

Types 21

Policy controlling writer defaults and parser behavior.

Note on Policy Naming:

This struct is named Json5Policy following the convention of format-specific policy structs (JsonPolicy, SdlPolicy). The CfParserConfig struct uses a different naming pattern for historical reasons (it predates the policy naming convention and has additional configuration beyond parsing behavior).

Note on lastKeyWins:

Unlike JsonPolicy which uses a JsonDuplicateKeyPolicy enum with three options (LAST_WINS, FIRST_WINS, ERROR), this struct uses a simple boolean. This is intentional: JSON5 is designed as a more lenient format for human-authored configuration files, where strict duplicate detection (ERROR) is rarely desired. The boolean provides a simpler API for the common case of choosing between first-wins and last-wins semantics. When useStrictJsonParser is enabled, the boolean maps to the corresponding enum value in the underlying JsonPolicy.

Fields
bool preferSignedIntegersPrefer signed integers when a value fits both signed and unsigned.
bool lastKeyWinsDuplicate keys policy: if true, last occurrence wins; if false, first wins. Unlike `JsonPolicy.duplicateKeyPolicy`, this is a boolean because JSON5's lenient nature makes the strict ERROR option ra...
size_t maxDepthMaximum nesting depth allowed during parsing to prevent runaway recursion.
bool sortKeysOnWriteWriter: sort object keys for deterministic output.
bool asciiOnlyWriteWriter: emit only ASCII by escaping non-ASCII code points.
bool useStrictJsonParserWhen true, delegate parsing to `ddn.data.json` for potentially faster strict JSON parsing.
enumJson5ErrorCode : ushort

A non-throwing error report produced by the JSON5 parser/writer.

UNKNOWNUnknown/unspecified error.
TRAILING_CONTENTTrailing non-whitespace/comment content after a complete root value.
UNEXPECTED_TOKENUnexpected token kind for the current parse state.
UNEXPECTED_EOFUnexpected end of input.
INVALID_TOKENTokenization failure (invalid UTF-8, malformed comment, etc.).
INVALID_NUMBERInvalid number literal syntax.
INVALID_STRINGInvalid string literal syntax.
INVALID_ESCAPEInvalid escape sequence in a string literal.
MAX_DEPTH_EXCEEDEDParser recursion limit exceeded.
INVALID_ARGUMENTInvalid argument passed to a helper API.
IO_ERRORI/O error while reading/writing.

Structured, non-throwing JSON5 error report.

Fields
size_t line1-based line number where the error occurred (0 if unknown).
size_t column1-based column number where the error occurred (0 if unknown).
size_t index0-based byte offset into the original input (0 if unknown).
Json5ErrorCode codeMachine-readable error category.
string messageHuman-readable message.
string contextExcerpt of the source around `index` with a caret line, if available.
Constructors
this(size_t line, size_t column, string message, Json5ErrorCode code = Json5ErrorCode.UNKNOWN, size_t index = 0, string context = "")Construct an error report.
enumJson5QuoteStyle : ubyte

Quote style used by the JSON5 writer.

DOUBLEEmit double quoted strings: `"..."`.
SINGLEEmit single quoted strings: `'...'`.
enumJson5WriteMode : ubyte

Output mode for the writer.

JSON5Emit JSON5 (allows unquoted keys, single quotes, NaN/Infinity, etc.).
JSONEmit strict JSON (RFC 8259 style).

Writer formatting options for JSON5 emission.

Fields:

  • pretty: enable multi-line pretty printing with indentation.
  • indentWidth: number of spaces per indentation level (used only when pretty).
  • quoteStyle: whether strings are emitted with single or double quotes.
  • asciiOnly: when true, escape non-ASCII as \uXXXX or \u{...}.
  • sortKeys: when true, object keys are emitted sorted for deterministic output.
  • maxDepth: maximum nesting depth allowed during writing; when exceeded, the writer emits null.
  • trailingCommas: when true, pretty mode emits a trailing comma after the last array element and the last object property; ignored in compact mode.
Fields
Json5WriteMode writeModeSelect whether to emit JSON5 or strict JSON.
bool prettyPretty-print output with indentation.
uint indentWidthNumber of spaces per indentation level when `pretty` is true.
Json5QuoteStyle quoteStyleString quoting style used by the writer.
Json5FloatFormat floatFormatFloating-point number formatting style.
uint floatPrecisionPrecision parameter for float formatting.
uint scientificExponentThresholdIf `floatFormat == AUTO`, switch to scientific when `abs(exponent) >= threshold`.
bool hexIntegersEmit integer values in hexadecimal form (`0x...`) when true.
Json5NegativeZeroStyle negativeZeroStyleControls how `-0.0` is emitted.
bool asciiOnlyEscape non-ASCII code points as \uXXXX.
bool sortKeysSort object keys for deterministic output.
bool trailingCommasEmit trailing commas in pretty mode for arrays/objects.
size_t maxDepthMaximum nesting depth allowed during writing to prevent runaway recursion.

Reusable scratch buffers for JSON5/JSON writing.

This structure allows caller-controlled reuse of temporary allocations across repeated serializations.

Currently used for:

  • Deterministic object serialization (sortKeys == true) via per-depth key buffers.
Fields
string[][] keyBuffersPer-depth buffers used to collect and sort object keys.
enumJson5FloatFormat : ubyte

Floating-point formatting mode used by the JSON5 writer.

SHORTESTUse the default D `to!string` representation.
FIXEDEmit fixed notation (`%.<precision>f`).
SCIENTIFICEmit scientific notation (`%.<precision>e`).
AUTOChoose between `SHORTEST` and `SCIENTIFIC` based on `scientificExponentThreshold`.

Controls how floating-point negative zero is emitted.

MINUS_ZERO_DOT_ZEROEmit negative zero as `-0.0`.
MINUS_ZEROEmit negative zero as `-0`.
aliasJson5Reviver = var delegate(const string key, var value) @safe

Reviver callback used to transform parsed values.

The callback is invoked in post-order (children first), similarly to JavaScript JSON.parse(text, reviver).

Arguments:

  • key: Object key / array index (as decimal string). Root is passed as `""`.
  • value: Current value.

The return value is the replacement value.

enumJson5PatchOpKind : ubyte

Kind of a JSON5 patch operation.

ADDAdd a value at `path`.
REMOVERemove the value at `path`.
REPLACEReplace the value at `path`.

A single JSON5 patch operation.

The path is a JSON Pointer-like path using `/` separators.

  • Root is `""`.
  • ~1 decodes to `/`.
  • ~0 decodes to `~`.
Fields
Json5PatchOpKind kindOperation kind.
string pathTarget path.
var valueValue for `ADD`/`REPLACE`.

Patch application error.

Fields
size_t opIndexIndex of the failing operation.
string pathPath associated with the failure.
string messageHuman-readable message.
enumJson5StreamResult : ubyte

Result of a streaming JSON5 parse attempt.

NEED_MOREThe parser needs more input to decide.
OKA complete JSON5 value was parsed successfully.
ERRORA syntax or lexical error occurred.

Incremental/streaming JSON5 parser that accepts input in chunks.

This API is intended for large inputs or network streams where the complete document may not be available at once.

Notes:

  • The parser produces at most one root JSON5 value.
  • After a successful parse (Json5StreamResult.OK), the instance becomes done; call reset() to parse another document.
  • When finish() has not been called yet, parse failures that look like “unexpected end of input” are reported as NEED_MORE.

    Examples

    import ddn.data.json5 : Json5StreamParser, Json5StreamResult, Json5Error;
    import ddn.var : var;
    
    Json5StreamParser sp;
    sp.push("{a:1,");
    var v; Json5Error err;
    assert(sp.tryParse(v, err) == Json5StreamResult.NEED_MORE);
    sp.push("b:2}");
    assert(sp.tryParse(v, err) == Json5StreamResult.OK);
    assert(v["b"].as!long == 2);
Methods
void push(const(char)[] chunk) @safeAppend a new chunk of input to the internal buffer.
void finish() @safeMark the stream as finished.
void reset() @safeReset the parser state and clear all buffered input.
bool done() @property const @safeTrue once a full root value has been successfully parsed.
size_t bufferedLength() @property const @safeCurrent buffered input size in bytes.
Json5StreamResult tryParse(out var value, out Json5Error err) @safeAttempt to parse the buffered data as a single JSON5 root value.
Constructors
this(const Json5Policy policy)Construct a streaming parser using `policy`.

Callbacks for SAX-style JSON5 parsing.

Any callback may be left null to ignore that event.

Event semantics:

  • onObjectStart / onObjectEnd are emitted for `{` / `}`.
  • onArrayStart / onArrayEnd are emitted for `[` / `]`.
  • onKey is emitted for each object property key, before its value.
  • onValue is emitted for scalar values only (null/bool/number/string).
Fields
void delegate() @safe onObjectStartCalled when an object begins (`{`).
void delegate() @safe onObjectEndCalled when an object ends (`}`).
void delegate() @safe onArrayStartCalled when an array begins (`[`).
void delegate() @safe onArrayEndCalled when an array ends (`]`).
void delegate(const string key) @safe onKeyCalled for each object key.
void delegate(const var value) @safe onValueCalled for each scalar value.
enumJson5TokenKind : ushort

Kinds of JSON5 tokens.

END
LBRACE
RBRACE
LBRACKET
RBRACKET
COLON
COMMA
STRING
IDENTIFIER
NUMBER
TRUE_LIT
FALSE_LIT
NULL_LIT
INF_LIT
NAN_LIT
COMMENT
ERROR

A single JSON5 token.

Fields
Json5TokenKind kindToken kind.
size_t line1-based line on which the token starts.
size_t column1-based column on which the token starts.
const(char)[] lexemeRaw slice of the input covering the token text (for STRING/IDENTIFIER/NUMBER).
size_t startIndexStart index in the source buffer (for reconstruction when `lexeme` is empty).
size_t endIndexEnd index (one past last) in the source buffer.

High-performance JSON5 lexer over a UTF‑8 buffer.

  • Skips BOM, whitespace, and comments.
  • Returns slices for identifiers, strings, and numbers without allocating.
  • Tracks line/column for diagnostics.
Methods
size_t line() @property const @safeCurrent 1-based line number.
size_t column() @property const @safeCurrent 1-based column number.
Json5Token nextToken() @safeReturn the next token from the stream.
Json5Token nextTokenWithComments() @safeReturn the next token, emitting COMMENT tokens instead of skipping them.
Constructors
this(const(char)[] input)Construct a lexer over `input`.

A small, non-throwing JSON5 recursive-descent parser that builds ddn.var directly.

Create an instance with input and policy, then call parseRoot(out var) to parse a value. On failure, parseRoot returns false and populates the provided Json5Error with line/column and a brief message.

Fields
Json5Lexer lxUnderlying lexer (exposed for diagnostics in tests).
Json5Token curCurrent token (public for testing and the outer wrapper).
Json5Policy policyParser policy (depth limits, preferences, etc.).
Methods
void advance() @safeAdvance to the next token.
bool parseRoot(out var v) @safeParse a root value into `out v`.
bool parseValue(out var outv, size_t depth) @safeParse a value at a given depth into `out v`.
bool parseArray(out var outv, size_t depth) @safeParse an array value; assumes `cur` is `[` on entry.
bool parseObject(out var outv, size_t depth) @safeParse an object value; assumes `cur` is `{` on entry.
bool fail(const(char)[] msg, const Json5ErrorCode code = Json5ErrorCode.UNEXPECTED_TOKEN) @safeRecord an error at the current position and return `false`.
Constructors
this(const(char)[] input, Json5Policy policy, ref Json5Error err)Construct a parser for `input` with `policy`, using `err` as the error sink.
classJson5Exception : Exception

Exception thrown when JSON5 parsing fails.

This exception includes source location information for error reporting.

Fields
size_t lineLine number where the error occurred (1-based)
size_t columnColumn number where the error occurred (1-based)
Constructors
this(string msg, size_t line, size_t column)Construct a Json5Exception.

Functions 25

fnbool parseJSON5(out var value, const(char)[] input, out Json5Error err) @safeParse JSON5 text from `input` into `value`.
fnbool parseJSON5(out var value, const(char)[] input, out Json5Error err, Json5Policy policy) @safeParse JSON5 text into a `var` value with custom policy.
fnbool parseJSON5(out var value, const(char)[] input, Json5Reviver reviver, out Json5Error err) @safeParse JSON5 text and apply `reviver` to each value.
fnvar parseJSON5(const(char)[] input) @safeConvenience overload that parses JSON5 text and returns the resulting value. Note: returns `var.init` on failure.
fnbool minify(out string output, const(char)[] input, out Json5Error err) @safeMinify JSON5 text by removing comments and optional whitespace.
fnstring minify(const(char)[] input) @safeConvenience overload that returns minified JSON5 text.
fnJson5PatchOp[] json5Diff(var from, var to) @safeCompute a patch transforming `from` into `to`.
fnbool json5Patch(ref var base, scope const Json5PatchOp[] ops, out Json5PatchError err) @safeApply a patch to `base`.
fnbool parseJSON5(out var value, ref File file, out Json5Error err, const Json5Policy policy = Json5Policy.init, size_t chunkSize = 16_384) @safeParse JSON5 data from an open `std.stdio.File`.
fnbool parseJSON5(R)(out var value, R input, out Json5Error err, const Json5Policy policy = Json5Policy.init, size_t chunkSize = 16_384) if ( isInputRange!R && (is(ElementType!R == ubyte) || isSomeChar!(ElementType!R)) ) @safeParse JSON5 data from an input range of `char` or `ubyte`.
fnbool parseJSON5Sax(const(char)[] input, ref Json5SaxHandler handler, out Json5Error err, const Json5Policy policy = Json5Policy.init) @safeParse JSON5 text and emit SAX-style events into `handler`.
fnstring toJSON5(const var value, const Json5WriteOptions opts = Json5WriteOptions.init) @safeSerialize a `var` to JSON5 text using the provided `opts`.
fnstring toJSON5(const var value, const Json5WriteOptions opts, ref Json5WriteScratch scratch) @safeSerialize a `var` to JSON5 text using the provided `opts` and reusable `scratch` buffers.
fnstring toJSON(const var value, const Json5WriteOptions opts = Json5WriteOptions.init) @safeSerialize a `var` to strict JSON text.
fnstring toJSON(const var value, const Json5WriteOptions opts, ref Json5WriteScratch scratch) @safeSerialize a `var` to strict JSON text using the provided `opts` and reusable `scratch` buffers.
fnbool load(out var obj, const string fileName, out Json5Error err) @safeLoad a JSON5 file from disk into `obj`.
fnbool save(const var obj, const string fileName, const Json5WriteOptions opts = Json5WriteOptions.init, out Json5Error err) @safeSave a `var` as JSON5 to disk.
fnbool parseJSON5NumericLiteral(out var value, const(char)[] text, const Json5Policy policy = Json5Policy.init) @safeParse a JSON5 numeric literal from `text` into `out value`.
fnbool parseJSON5StringLiteral(out string result, const(char)[] text, out Json5ErrorCode errCode) @safeDecode a JSON5 string literal (single or double quoted) into a D `string`.
fnbool parseJSON5StringLiteral(out string result, const(char)[] text) @safeDecode a JSON5 string literal.
fnbool isValidUnquotedKey(const(char)[] key) @safe
fnauto parseJson5Cdm(Builder = CdmBuilder)(const(char)[] input, string source = "") @trustedParse JSON5 text.
fnauto parseJson5Cdm(Builder = CdmBuilder)(File file) @safeParse JSON5 file.
fnbool parseJson5Cdm(out CdmDocument doc, const(char)[] input, Json5Error * err, string source = "", Json5Policy policy = Json5Policy.init) @safeNon-throwing parse variant that produces a `CdmDocument`.
fnstring toJSON5Cdm(const ref CdmDocument doc, Json5WriteOptions opts = Json5WriteOptions.init) @safeSerialize a CDM document to JSON5 text.