ddn.data.json5¶
JSON5 parsing and serialization support for the D programming language.
Overview¶
This module provides comprehensive support for JSON5, a superset of JSON that aims to be easier for humans to write and maintain. It includes a full-featured parser and writer that maps JSON5 values to and from ddn.var.
JSON5 Features Supported:
- Comments:
//line and/* */block comments - Trailing commas in arrays and objects
- Unquoted keys when identifier-compatible
- Single-quoted strings and escape sequences
- Numbers with leading
+, hex (0x...), leading/trailing decimal points - Special numbers:
NaN,Infinity,-Infinity - UTF-8 BOM accepted at the beginning of input
Enums¶
Json5Feature¶
Feature switches for JSON5 support.
| Member | Description |
|---|---|
COMMENTS |
Allow // and /* */ comments |
TRAILING_COMMAS |
Allow trailing commas in arrays/objects |
UNQUOTED_KEYS |
Allow unquoted identifier keys |
SINGLE_QUOTED_STRINGS |
Allow 'single quoted' strings |
HEX_NUMBERS |
Allow 0xDEADBEEF notation |
LEADING_DECIMAL_POINT |
Allow .5 as 0.5 |
TRAILING_DECIMAL_POINT |
Allow 5. as 5.0 |
EXPLICIT_PLUS |
Allow +1.5 notation |
SPECIAL_NUMBERS |
Allow NaN, Infinity, -Infinity |
LINE_CONTINUATION |
Allow backslash line continuation in strings |
Json5ErrorCode¶
Error codes returned by the JSON5 parser.
| Member | Description |
|---|---|
NONE |
No error |
UNEXPECTED_EOF |
Unexpected end of input |
UNEXPECTED_TOKEN |
Unexpected token encountered |
INVALID_NUMBER |
Invalid numeric literal |
INVALID_STRING |
Invalid string literal |
INVALID_ESCAPE |
Invalid escape sequence |
UNTERMINATED_STRING |
String not properly terminated |
UNTERMINATED_COMMENT |
Block comment not closed |
DUPLICATE_KEY |
Duplicate key in object |
MAX_DEPTH_EXCEEDED |
Nesting depth limit exceeded |
INVALID_UTF8 |
Invalid UTF-8 encoding |
Json5QuoteStyle¶
Quote style for string output.
| Member | Description |
|---|---|
DOUBLE |
Use double quotes (") |
SINGLE |
Use single quotes (') |
AUTO |
Choose based on content (fewer escapes) |
Json5WriteMode¶
Output format mode.
| Member | Description |
|---|---|
JSON5 |
JSON5 format (unquoted keys, single quotes, etc.) |
JSON |
Strict JSON format |
Json5FloatFormat¶
Floating-point number formatting options.
| Member | Description |
|---|---|
DEFAULT |
Default formatting |
SCIENTIFIC |
Scientific notation |
FIXED |
Fixed-point notation |
Json5NegativeZeroStyle¶
How to handle negative zero (-0.0).
| Member | Description |
|---|---|
PRESERVE |
Preserve -0.0 |
POSITIVE |
Convert to 0.0 |
Json5StreamResult¶
Result codes for streaming parser operations.
| Member | Description |
|---|---|
OK |
Operation succeeded |
NEED_MORE |
More input needed |
ERROR |
Parse error occurred |
DONE |
Parsing complete |
Json5TokenKind¶
Token types produced by the lexer.
| Member | Description |
|---|---|
EOF |
End of input |
LBRACE |
{ |
RBRACE |
} |
LBRACKET |
[ |
RBRACKET |
] |
COLON |
: |
COMMA |
, |
STRING |
String literal |
NUMBER |
Numeric literal |
TRUE |
true |
FALSE |
false |
NULL |
null |
IDENTIFIER |
Unquoted identifier |
NAN |
NaN |
INFINITY |
Infinity |
NEG_INFINITY |
-Infinity |
Json5PatchOpKind¶
JSON Patch operation types.
| Member | Description |
|---|---|
ADD |
Add a value |
REMOVE |
Remove a value |
REPLACE |
Replace a value |
MOVE |
Move a value |
COPY |
Copy a value |
TEST |
Test a value |
Structs¶
Json5Policy¶
Configuration for JSON5 parsing behavior.
Fields:
| Name | Type | Description |
|---|---|---|
features |
uint |
Bitmask of enabled Json5Feature flags |
maxDepth |
uint |
Maximum nesting depth (default: 512) |
maxStringLength |
size_t |
Maximum string length |
Json5Error¶
Error information from parsing operations.
Fields:
| Name | Type | Description |
|---|---|---|
code |
Json5ErrorCode |
Error code |
message |
string |
Human-readable error message |
line |
size_t |
Line number (1-based) |
column |
size_t |
Column number (1-based) |
Json5WriteOptions¶
Configuration for JSON5 serialization.
Fields:
| Name | Type | Description |
|---|---|---|
writeMode |
Json5WriteMode |
Output format (JSON5 or JSON) |
quoteStyle |
Json5QuoteStyle |
String quote style |
pretty |
bool |
Enable pretty-printing |
indentWidth |
uint |
Spaces per indent level |
sortKeys |
bool |
Sort object keys alphabetically |
trailingCommas |
bool |
Add trailing commas (JSON5 only) |
maxDepth |
uint |
Maximum serialization depth |
Json5WriteScratch¶
Reusable scratch buffers for serialization to reduce allocations.
Usage:
Json5WriteScratch scratch;
foreach (item; items) {
string json = toJSON5(item, Json5WriteOptions.init, scratch);
// process json...
}
Json5PatchOp¶
A single JSON Patch operation.
Fields:
| Name | Type | Description |
|---|---|---|
op |
Json5PatchOpKind |
Operation type |
path |
string |
JSON Pointer path |
from |
string |
Source path (for move/copy) |
value |
var |
Value (for add/replace/test) |
Json5PatchError¶
Error information from patch operations.
Fields:
| Name | Type | Description |
|---|---|---|
message |
string |
Error description |
opIndex |
size_t |
Index of failed operation |
Json5Token¶
A lexical token from JSON5 input.
Fields:
| Name | Type | Description |
|---|---|---|
kind |
Json5TokenKind |
Token type |
text |
const(char)[] |
Token text |
line |
size_t |
Line number |
column |
size_t |
Column number |
Json5Lexer¶
Low-level lexical analyzer for JSON5 input.
Json5Parser¶
Low-level JSON5 parser.
Json5StreamParser¶
Streaming JSON5 parser for incremental input processing.
Json5SaxHandler¶
SAX-style event handler for streaming JSON5 parsing.
Callback Fields:
| Name | Type | Description |
|---|---|---|
onNull |
bool delegate() |
Called for null values |
onBool |
bool delegate(bool) |
Called for boolean values |
onNumber |
bool delegate(var) |
Called for numeric values |
onString |
bool delegate(string) |
Called for string values |
onStartArray |
bool delegate() |
Called at array start |
onEndArray |
bool delegate() |
Called at array end |
onStartObject |
bool delegate() |
Called at object start |
onKey |
bool delegate(string) |
Called for object keys |
onEndObject |
bool delegate() |
Called at object end |
Functions¶
parseJSON5¶
Parses a JSON5 string into a var value.
Parameters:
| Name | Type | Description |
|---|---|---|
value |
out var |
Receives the parsed value |
input |
const(char)[] |
JSON5 input string |
err |
out Json5Error |
Receives error information on failure |
Returns: true on success, false on parse error.
Example:
Json5Error err;
var v;
if (parseJSON5(v, "{a: 1, b: 'hello',}", err)) {
assert(v["a"].as!long == 1);
assert(v["b"].as!string == "hello");
} else {
writefln("Error at %d:%d - %s", err.line, err.column, err.message);
}
parseJSON5 (with reviver)¶
Parses JSON5 with a reviver function for value transformation.
Parameters:
| Name | Type | Description |
|---|---|---|
value |
out var |
Receives the parsed value |
input |
const(char)[] |
JSON5 input string |
reviver |
Json5Reviver |
Transformation function |
err |
out Json5Error |
Receives error information on failure |
Returns: true on success, false on parse error.
parseJSON5 (from File)¶
Parses JSON5 from a file handle.
parseJSON5 (from Range)¶
Parses JSON5 from an input range.
parseJSON5Sax¶
Parses JSON5 using SAX-style event callbacks.
Parameters:
| Name | Type | Description |
|---|---|---|
input |
const(char)[] |
JSON5 input string |
handler |
ref Json5SaxHandler |
Event handler callbacks |
err |
out Json5Error |
Receives error information on failure |
Returns: true on success, false on error or handler abort.
parseJSON5NumericLiteral¶
bool parseJSON5NumericLiteral(out var value, const(char)[] text, const Json5Policy policy = Json5Policy.init) @safe
Parses a single JSON5 numeric literal.
Parameters:
| Name | Type | Description |
|---|---|---|
value |
out var |
Receives the parsed number |
text |
const(char)[] |
Numeric literal text |
policy |
Json5Policy |
Parsing policy |
Returns: true on success, false on invalid input.
parseJSON5StringLiteral¶
bool parseJSON5StringLiteral(out string result, const(char)[] text, out Json5ErrorCode errCode) @safe
Parses a single JSON5 string literal.
Parameters:
| Name | Type | Description |
|---|---|---|
result |
out string |
Receives the decoded string |
text |
const(char)[] |
String literal text (including quotes) |
errCode |
out Json5ErrorCode |
Receives error code on failure |
Returns: true on success, false on invalid input.
toJSON5¶
Serializes a var to JSON5 text.
Parameters:
| Name | Type | Description |
|---|---|---|
value |
const var |
Value to serialize |
opts |
Json5WriteOptions |
Serialization options |
Returns: JSON5-formatted string.
Example:
var data;
data["name"] = "example";
data["values"] = [1, 2, 3];
string json5 = toJSON5(data);
// Output: {name:'example',values:[1,2,3]}
toJSON5 (with scratch)¶
Serializes a var to JSON5 text using reusable scratch buffers.
toJSON¶
Serializes a var to strict JSON text.
Parameters:
| Name | Type | Description |
|---|---|---|
value |
const var |
Value to serialize |
opts |
Json5WriteOptions |
Serialization options |
Returns: JSON-formatted string.
Notes:
- All keys are quoted with double quotes.
NaNandInfinityare emitted asnull.- No trailing commas.
Example:
var data;
data["name"] = "example";
data["values"] = [1, 2, 3];
string json = toJSON(data);
// Output: {"name":"example","values":[1,2,3]}
toJSON (with scratch)¶
Serializes a var to strict JSON text using reusable scratch buffers.
minify¶
Removes comments and unnecessary whitespace from JSON5 input.
Parameters:
| Name | Type | Description |
|---|---|---|
input |
const(char)[] |
JSON5 input string |
Returns: Minified JSON5 string.
Example:
json5Diff¶
Computes the difference between two var values as JSON Patch operations.
Parameters:
| Name | Type | Description |
|---|---|---|
from |
var |
Original value |
to |
var |
Target value |
Returns: Array of patch operations to transform from into to.
Constants¶
JSON5_DEFAULT_FEATURES¶
Default feature flags enabling all standard JSON5 extensions.
See Also¶
ddn.var— Dynamic value type used for JSON5 data representation.ddn.adam— Memory-efficient alternative tovar.ddn.util.json_escape— String escaping utilities used internally.