toJSON

Template function that converts any object to JSON

JSONValue
toJSON
(
T
)
()

Examples

Converting common types

assert(5.toJSON!int == JSONValue(5));
assert(4.toJSON != JSONValue(5));
assert(5.4.toJSON == JSONValue(5.4));
assert(toJSON("test") == JSONValue("test"));
assert(toJSON(JSONValue("test")) == JSONValue("test"));

Converting InputRanges

assert([1, 2].toJSON.toString == "[1,2]");

User structs

Point p;
assert(toJSON(p).toString == q{{"x":0,"y":1}});

Array of structs

Point[] ps = [Point(-1, 1), Point(2, 3)];
assert(toJSON(ps).toString == q{[{"x":-1,"y":1},{"x":2,"y":3}]});

User class

PointC p = new PointC(1, -2);
assert(toJSON(p).toString == q{{"x":1,"y":-2}});

User class with private fields

PointPrivate p = new PointPrivate(-1, 2);
assert(toJSON(p).toString == q{{"x":-1,"y":2}});

Array of classes

PointC[] ps = [new PointC(-1, 1), new PointC(2, 3)];
assert(toJSON(ps).toString == q{[{"x":-1,"y":1},{"x":2,"y":3}]});

Associative array

string[int] aa = [0 : "a", 1 : "b"];
// In JSON (D) only string based associative arrays are supported, so:
assert(aa.toJSON.toString == q{{"0":"a","1":"b"}});
Point[int] aaStruct = [0 : Point(-1, 1), 1 : Point(2, 0)];
assert(aaStruct.toJSON.toString == q{{"0":{"x":-1,"y":1},"1":{"x":2,"y":0}}});

Overloaded toJSON

class A
{
    double x = 0;
    double y = 1;
    JSONValue toJSON()
    {
        JSONValue[string] json;
        json["x"] = x;
        return JSONValue(json);
    }

}

auto a = new A;
assert(a.toJSON.toString == q{{"x":0}});

class B
{
    double x = 0;
    double y = 1;
}


// Both templates will now work for B, so this is ambiguous in D. 
// Under dmd it looks like the toJSON!T that is loaded first is the one used
JSONValue toJSON(T : B)(T b)
{
    JSONValue[string] json;
    json["x"] = b.x;
    return JSONValue(json);
}

auto b = new B;
assert(b.toJSON.toString == q{{"x":0,"y":1}});

class Z
{
    double x = 0;
    double y = 1;
    // Adding an extra value
    JSONValue toJSON()
    {
        JSONValue[string] json = painlessjson.toJSON!Z(this).object;
        json["add"] = "bla".toJSON;
        return JSONValue(json);
    }

}

auto z = new Z;
assert(z.toJSON.toString == q{{"x":0,"y":1,"add":"bla"}});

Meta