toJSON
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
value | The value to serialize. |
opts | Options 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 defaultSerialize a var value to JSON using the provided scratch buffers.
This overload allows reusing scratch buffers across multiple serializations to reduce GC pressure.
Parameters
value | The value to serialize. |
opts | Options controlling serialization behavior. |
scratch | Reusable scratch buffers. |
Returns
The JSON string representation.
fn
string toJSON(const var value, JsonReplacer replacer, JsonWriteOptions opts = JsonWriteOptions.init) @safeSerialize 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
value | The value to serialize. |
replacer | Delegate to transform/filter each value. May be null (no transformation). |
opts | Options 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"}`);