1 /* 2 Purpose : Simple JSON query tool 3 Author : Ky-Anh Huynh 4 License : MIT 5 Date : 2017 Sep 09th 6 */ 7 8 module dusybox.json; 9 10 import std.json; 11 import std.conv; 12 import std.algorithm; 13 import std.array: array; 14 15 string json_resolve(in JSONValue j, in string symbol) { 16 auto symbol_n = symbol[0..$]; 17 if (symbol.length > 0 && symbol[0] == '.') { 18 symbol_n = symbol[1..$]; 19 return (symbol_n in j) 20 ? (j[symbol_n].type() == JSON_TYPE.STRING 21 ? j[symbol_n].str 22 : to!string(j[symbol_n])) 23 : symbol; 24 } 25 else { 26 return symbol; 27 } 28 } 29 30 string[] json_resolve(in JSONValue j, in string[] symbols) { 31 string[] results; 32 33 if (symbols.length > 0) { 34 results = symbols.map!(a => j.json_resolve(a)).array; 35 } 36 else { 37 results ~= j.toString; 38 } 39 40 return results; 41 } 42 43 unittest { 44 auto jsond = parseJSON("{\"a\": 1, \"b\": \"x\", \"c\": {\"ca\": 0}}"); 45 46 assert(jsond.json_resolve(".a") == "1", "Integer value should be resolved to a string."); 47 assert(jsond.json_resolve(".x") == ".x", "Unknown key should be resolved to key per-se."); 48 assert(jsond.json_resolve(".c") == "{\"ca\":0}", "Object should be resolved to string version of them."); 49 50 assert(jsond.json_resolve([".a", ".x"]) == ["1", ".x"]); 51 assert(jsond.json_resolve([".a", " ", "1"]) == ["1", " ", "1"]); 52 53 string[] empty_arr; 54 assert(jsond.json_resolve(empty_arr) == [jsond.toString]); 55 }