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 2

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`.