Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Serialize D types to json

View json.d
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
module json;
 
import std.conv;
import std.array;
import std.traits;
 
string json(T) (T obj) {
static if (is(typeof(obj) == string)) {
return "\"" ~ obj.replace("\\", "\\\\").replace("\"", "\\\"") ~ "\"";
} else static if (isBasicType!(typeof(obj))) {
return to!string(obj);
} else static if (isArray!(typeof(obj))) {
string res = "";
 
foreach (val; obj) {
res ~= json(val) ~ ",";
}
 
if (res.length > 0) res = res[0..$-1];
 
return "[" ~ res ~ "]";
} else {
string res = "";
 
foreach (mem; __traits(allMembers, typeof(obj))) {
static if (!isCallable!(__traits(getMember, obj, mem)) && __traits(compiles, json(__traits(getMember, obj, mem)))) {
auto val = __traits(getMember, obj, mem);
res ~= "\"" ~ mem ~ "\":" ~ json(val) ~ ",";
}
}
 
if (res.length > 0) res = res[0..$-1];
 
return "{" ~ res ~ "}";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.