toJSON

fnstring toJSON(const var value, JsonWriteOptions opts = JsonWriteOptions.init) @safe

Serialize a var value to a JSON string.

This function converts a var value tree into its JSON text representation. The output is strictly RFC 8259 compliant.

Parameters

valueThe value to serialize.
optsOptions controlling serialization behavior.

Returns

The JSON string representation.

Examples

import ddn.data.json : toJSON;
import ddn.var : var;

var v;
v["name"] = "John";
v["age"] = 30;
auto json = toJSON(v);
assert(json == `{"age":30,"name":"John"}`); // keys sorted by default
fnstring toJSON(const var value, JsonWriteOptions opts, ref JsonWriteScratch scratch) @safe

Serialize a var value to JSON using the provided scratch buffers.

This overload allows reusing scratch buffers across multiple serializations to reduce GC pressure.

Parameters

valueThe value to serialize.
optsOptions controlling serialization behavior.
scratchReusable scratch buffers.

Returns

The JSON string representation.
fnstring toJSON(const var value, JsonReplacer replacer, JsonWriteOptions opts = JsonWriteOptions.init) @safe

Serialize a var value to JSON with a replacer function.

The replacer is called for each value before serialization, allowing transformation or filtering. This is similar to JavaScript's JSON.stringify(value, replacer).

Parameters

valueThe value to serialize.
replacerDelegate to transform/filter each value. May be null (no transformation).
optsOptions controlling serialization behavior.

Returns

The JSON string representation.

Examples

import ddn.data.json : toJSON, JsonReplacer;
import ddn.var : var;

// Filter out "password" keys
JsonReplacer rep = (const string key, var value) @safe {
  if (key == "password")
     return var.init;  // omit from output
  return value;
};

var v;
v["user"] = "alice";
v["password"] = "secret";
auto json = toJSON(v, rep);
assert(json == `{"user":"alice"}`);