Skip to content

ddn.util.json_escape

Working, copy-pastable examples for ddn.util.json_escape.

This module provides small, focused helpers for producing correctly escaped JSON/JSON5 string literals. It is primarily useful when you are building serializers, log formats, or protocol messages and want to avoid re-implementing JSON escaping.

Escape a string (no surrounding quotes)

escapeJSONString returns the escaped contents without adding surrounding quotes.

/+ dub.sdl:
    name "json-escape-basic"
    dependency "ddn" path="../.."
+/
import ddn.util.json_escape : escapeJSONString;
import std.stdio : writeln;

void main() {
    auto raw = "hello\n\"world\"";
    auto escaped = escapeJSONString(raw);
    writeln(escaped);

    // Newline and quote are escaped.
    assert(escaped == "hello\\n\\\"world\\\"");
}

Choose quote style (' vs ")

If you plan to wrap the result in single quotes (JSON5), pass quote = '\'' so that single quotes get escaped too.

/+ dub.sdl:
    name "json-escape-quote"
    dependency "ddn" path="../.."
+/
import ddn.util.json_escape : escapeJSONString;
import std.stdio : writeln;

void main() {
    auto raw = "it's \"fine\"";

    auto forDoubleQuotes = escapeJSONString(raw, '"');
    auto forSingleQuotes = escapeJSONString(raw, '\'');

    writeln(forDoubleQuotes);
    writeln(forSingleQuotes);

    // If you wrap with double quotes, only `"` must be escaped.
    assert(forDoubleQuotes == "it's \\\"fine\\\"");

    // If you wrap with single quotes, the apostrophe must be escaped too.
    assert(forSingleQuotes == "it\\'s \\\"fine\\\"");
}

ASCII-only output (escape non-ASCII as \uXXXX / surrogate pairs)

Some systems expect ASCII-only payloads. Set asciiOnly = true to escape non-ASCII code points.

/+ dub.sdl:
    name "json-escape-ascii-only"
    dependency "ddn" path="../.."
+/
import ddn.util.json_escape : escapeJSONString;
import std.stdio : writeln;

void main() {
    // U+1F44D THUMBS UP SIGN
    auto raw = "ok 👍";
    auto ascii = escapeJSONString(raw, '"', true);
    writeln(ascii);

    // Should contain only ASCII characters.
    foreach (ubyte b; cast(const(ubyte)[])ascii) {
        assert(b < 0x80);
    }
}

Write a quoted JSON string directly to a buffer

writeJSONString writes a fully quoted JSON/JSON5 string to an output buffer (e.g. Appender!string).

/+ dub.sdl:
    name "json-escape-write"
    dependency "ddn" path="../.."
+/
import ddn.util.json_escape : writeJSONString;
import std.array : appender;
import std.stdio : writeln;

void main() {
    auto outBuf = appender!string();
    writeJSONString("say \"hi\"\n", outBuf);

    auto text = outBuf.data;
    writeln(text);

    // Includes surrounding quotes and escaped content.
    assert(text == "\"say \\\"hi\\\"\\n\"");
}