ddn.util.json_escape

JSON/JSON5 String Escaping Utilities

This module provides efficient, allocation-aware routines for escaping strings according to JSON and JSON5 specifications. It is used internally by ddn.var and ddn.data.json5 to produce correctly escaped string literals during serialization.

Features:

  • Fast-path detection: strings that require no escaping are returned as-is.
  • Standard short escapes for common control characters: \b, \f, \n, \r, \t.
  • Unicode escapes (\uXXXX) for control characters and, optionally, all non-ASCII code points.
  • Surrogate-pair handling for code points above U+FFFF when asciiOnly is enabled.
  • Configurable quote character (`"` or `'`) to support both JSON and JSON5 single-quoted strings.
  • @safe implementations suitable for use in memory-safe D code.

Example:

import ddn.util.json_escape;
import std.array : appender;

// Escape a string (without surrounding quotes)
assert(escapeJSONString("hello\nworld") == "hello\\nworld");

// Write a quoted JSON string directly to an output buffer
auto buf = appender!string();
writeJSONString("say \"hi\"", buf);
assert(buf.data == `"say \"hi\""`);

See Also

ddn.var.toJSON, ddn.data.json5.toJSON5

Functions 6

private fnvoid writeUnicodeEscape(Sink)(ref Sink sink, ushort v) if (is(typeof(sink.put("test"))) || is(typeof(sink.put('c')))) @safeWrite a `\uXXXX` escape sequence for a 16-bit value.
private fnvoid writeCodePointEscaped(Sink)(ref Sink sink, dchar dc) if (is(typeof(sink.put("test"))) || is(typeof(sink.put('c')))) @safeWrite a Unicode code point as escaped JSON.
private fnvoid escapeToSink(Sink)(scope const(char)[] s, ref Sink sink, const char quote, const bool asciiOnly) if (is(typeof(sink.put("test"))) || is(typeof(sink.put('c')))) @safeEscape the contents of a UTF-8 string and write to a sink.
private fndchar tryDecodeUTF8(scope const(char)[] s, size_t pos, out size_t bytesConsumed) @safeAttempt to decode a UTF-8 code point from the string at position `pos`.
fnstring escapeJSONString(const string s, const char quote = '"', const bool asciiOnly = false) @safeEscape a UTF-8 string for inclusion in a JSON/JSON5 string literal.
fnvoid writeJSONString(Sink)(scope const(char)[] s, ref Sink sink, const bool asciiOnly = false, const char quote = '"') if (is(typeof(sink.put("test"))) || is(typeof(sink.put('c')))) @safeWrite a JSON/JSON5 string literal (including surrounding quotes) to `sink`.

Variables 1

private enumvarHEX = "0123456789ABCDEF"

Hex digits for escape sequence encoding.