Last active
August 29, 2015 13:56
-
-
Save bithavoc/8958788 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std.stdio : writeln; | |
import std.json; | |
void main() { | |
JSONValue[] values = [parseJSON("28"), | |
parseJSON("\"hello world\""), | |
parseJSON(q{{"name": "Johan"}}), | |
parseJSON("[2,3]"), | |
parseJSON("true"), | |
parseJSON("false"), | |
parseJSON("null")]; | |
foreach(ref v; values) { | |
printJSON(v); | |
} | |
/* | |
Output: | |
JSON Type: INTEGER | |
Number Integer: 28 | |
JSON Type: STRING | |
String: hello world | |
JSON Type: OBJECT | |
Object: 1 properties | |
Property name | |
JSON Type: STRING | |
String: Johan | |
JSON Type: ARRAY | |
Array: 2 items | |
Index 0 | |
JSON Type: INTEGER | |
Number Integer: 2 | |
Index 1 | |
JSON Type: INTEGER | |
Number Integer: 3 | |
JSON Type: TRUE | |
(True) | |
JSON Type: FALSE | |
(False) | |
JSON Type: NULL | |
(Null) | |
*/ | |
} | |
void printJSON(JSONValue val, int level = 0) { | |
if(val == JSONValue.init) { | |
return; // uninitialized, don't do anything with val | |
} | |
print(level, "JSON Type: ", val.type); | |
switch(val.type) { | |
case JSON_TYPE.STRING: | |
print(level, "String: ", val.str); | |
break; | |
case JSON_TYPE.INTEGER: | |
print(level, "Number Integer: ", val.integer); | |
break; | |
case JSON_TYPE.FLOAT: | |
print(level, "Number Floating: ", val.floating); | |
break; | |
case JSON_TYPE.OBJECT: | |
writeln("Object: ", val.object.keys.length, " properties"); | |
foreach(string propName; val.object.keys) { | |
print(level + 2, "Property ", propName); | |
printJSON(val.object[propName], level + 3); | |
} | |
break; | |
case JSON_TYPE.ARRAY: | |
print(level, "Array: ", val.array.length, " items"); | |
foreach(i, JSONValue item; val.array) { | |
print(level + 2, "Index ", i); | |
printJSON(item, level + 3); | |
} | |
break; | |
case JSON_TYPE.TRUE: | |
print(level, "(True)"); | |
break; | |
case JSON_TYPE.FALSE: | |
print(level, "(False)"); | |
break; | |
case JSON_TYPE.NULL: | |
print(level, "(Null)"); | |
break; | |
default: | |
assert(false, std.string.format("Unknown JSON_TYPE %s", val.type)); | |
break; | |
} | |
} | |
void print(T...)(in int level, in T args) { | |
import std.range : repeat, chain, join; | |
import std.stdio : write; | |
import std.conv : to; | |
auto indent = ' '.repeat(level); | |
indent.write; | |
foreach(arg; args) { | |
write(to!string(arg)); | |
} | |
write("\n"); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment