Skip to content

Instantly share code, notes, and snippets.

@Overv
Last active January 2, 2016 09:19

Revisions

  1. Overv revised this gist Jan 6, 2014. 1 changed file with 10 additions and 0 deletions.
    10 changes: 10 additions & 0 deletions json.d
    Original file line number Diff line number Diff line change
    @@ -9,6 +9,16 @@ string json(T) (T obj) {
    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 = "";

  2. Overv created this gist Jan 6, 2014.
    26 changes: 26 additions & 0 deletions json.d
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    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 {
    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 ~ "}";
    }
    }