Function toJSON

Converts the given JSON document(s) to its string representation.

string toJSON(GeneratorOptions options = GeneratorOptions.init) (
  JSONValue value
);

string toJSON(GeneratorOptions options = GeneratorOptions.init, Input) (
  Input nodes
)
if (isJSONParserNodeInputRange!Input);

string toJSON(GeneratorOptions options = GeneratorOptions.init, Input) (
  Input tokens
)
if (isJSONTokenInputRange!Input);

string toJSON(GeneratorOptions options = GeneratorOptions.init, String) (
  JSONToken!String token
);

The input can be a JSONValue, or an input range of either JSONToken or JSONParserNode elements. By default, the generator will use newlines and tabs to pretty-print the result. Use the options template parameter to customize this.

Parameters

NameDescription
value A single JSON document
nodes A set of JSON documents encoded as single parser nodes. The nodes must be in valid document order, or the parser result will be undefined.
tokens List of JSON tokens to be converted to strings. The tokens may occur in any order and are simply appended in order to the final string.
token A single token to convert to a string

Returns

Returns a JSON formatted string.

See also

writeJSON, toPrettyJSON

Example

JSONValue value = true;
assert(value.toJSON() == "true");

Example

auto a = toJSONValue(`{"a": [], "b": [1, {}]}`);

// pretty print:
// {
//     "a": [],
//     "b": [
//         1,
//         {},
//     ]
// }
assert(
    a.toJSON() == "{\n\t\"a\": [],\n\t\"b\": [\n\t\t1,\n\t\t{}\n\t]\n}" ||
    a.toJSON() == "{\n\t\"b\": [\n\t\t1,\n\t\t{}\n\t],\n\t\"a\": []\n}"
);

// write compact JSON (order of object fields is undefined)
assert(
    a.toJSON!(GeneratorOptions.compact)() == `{"a":[],"b":[1,{}]}` ||
    a.toJSON!(GeneratorOptions.compact)() == `{"b":[1,{}],"a":[]}`
);