1 /// `toJSON!T` converts a instance of `T` to a `JSONValue` 2 module internal.tojson; 3 4 import std.json; 5 import std.conv; 6 import std.range; 7 import std.traits; 8 import std.string; 9 import std.algorithm; 10 import std.exception; 11 import std.typetuple; 12 import std.typecons : staticIota; 13 import internal.attribute; 14 15 // Primitive Type Conversions ----------------------------------------------------------- 16 /// convert a bool to a JSONValue 17 JSONValue toJSON(T : bool)(T val) { 18 return JSONValue(val); 19 } 20 21 /// convert a string to a JSONValue 22 JSONValue toJSON(T : string)(T val) { 23 return JSONValue(val); 24 } 25 26 /// convert a floating point value to a JSONValue 27 JSONValue toJSON(T : real)(T val) if (!is(T == enum)) { 28 return JSONValue(val); 29 } 30 31 /// convert a signed integer to a JSONValue 32 JSONValue toJSON(T : long)(T val) if (isSigned!T && !is(T == enum)) { 33 return JSONValue(val); 34 } 35 36 /// convert an unsigned integer to a JSONValue 37 JSONValue toJSON(T : ulong)(T val) if (isUnsigned!T && !is(T == enum)) { 38 return JSONValue(val); 39 } 40 41 /// convert an enum name to a JSONValue 42 JSONValue toJSON(T)(T val) if (is(T == enum)) { 43 JSONValue json; 44 json.str = to!string(val); 45 return json; 46 } 47 48 /// convert a homogenous array into a JSONValue array 49 JSONValue toJSON(T)(T args) if (isArray!T && !isSomeString!T) { 50 static if (isDynamicArray!T) { 51 if (args is null) { return JSONValue(null); } 52 } 53 JSONValue[] jsonVals; 54 foreach(arg ; args) { 55 jsonVals ~= toJSON(arg); 56 } 57 JSONValue json; 58 json.array = jsonVals; 59 return json; 60 } 61 62 /// convert a set of heterogenous values into a JSONValue array 63 JSONValue toJSON(T...)(T args) { 64 JSONValue[] jsonVals; 65 foreach(arg ; args) { 66 jsonVals ~= toJSON(arg); 67 } 68 JSONValue json; 69 json.array = jsonVals; 70 return json; 71 } 72 73 /// convert a associative array into a JSONValue object 74 JSONValue toJSON(T)(T map) if (isAssociativeArray!T) { 75 assert(is(KeyType!T : string), "toJSON requires string keys for associative array"); 76 if (map is null) { return JSONValue(null); } 77 JSONValue[string] obj; 78 foreach(key, val ; map) { 79 obj[key] = toJSON(val); 80 } 81 JSONValue json; 82 json.object = obj; 83 return json; 84 } 85 86 JSONValue toJSON(T)(T obj) if (!isBuiltinType!T) { 87 static if (is (T == class)) { 88 if (obj is null) { return JSONValue(null); } 89 } 90 return obj.convertToJSON(); 91 } 92