diff --git a/.gitignore b/.gitignore index a173085694215cc2b742031c2c7155cb0e848373..9ac2089936949b7752b876557bc35499ed0d61aa 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ .ccls-cache +json2table diff --git a/Makefile b/Makefile index f37d52bf64ee1e497b455a58b7270a63e6b7653b..f8ab92be918532c58303866951f1ca1b6bc844ba 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,9 @@ -CXX ?= g++ -O3 +CXX ?= g++ build: - $(CXX) json2table.cc -std=c++17 lib/fort.c -o json2table + $(CXX) -O3 json2table.cc -std=c++17 lib/fort.c -o json2table +install: build + cp json2table /usr/bin/ diff --git a/json2table.cc b/json2table.cc index 005a05068c8d5f71f05c6e262a0e3ffa6909b8ae..01cbaf48be0aa215306f9b44bde12c3e02fde021 100644 --- a/json2table.cc +++ b/json2table.cc @@ -27,6 +27,31 @@ inline string json_to_string(json j) { return "UNKNOWN"; } +void naive_json_access_path(json &input, rlib::string json_path) { + for(auto &next : json_path.split('/')) { + if(!next.empty()) { + if(input.is_object()) { + // Simplest case. + input = input[next]; + } + else if(input.is_array()) { + // Do this for every element. + json result_json_arr = json::array(); + for(auto &[_, item] : input.items()) { + if(item.is_object()) + result_json_arr.push_back(item[next]); + else + throw std::invalid_argument("json_path is not valid for json. No element `" + next + "` found in json input. (note that I support only one-level array iterate)"); + } + input = std::move(result_json_arr); + } + else { + throw std::invalid_argument("json_path is not valid for json. No element `" + next + "` found in json input. "); + } + } + } +} + int main(int argc, char **argv) { rlib::opt_parser args(argc, argv); if(args.getBoolArg("-h", "--help")) { @@ -35,13 +60,10 @@ int main(int argc, char **argv) { return 1; } - auto json_path = args.getSubCommand("").replace("\\", "/").strip("/"); + auto json_path = args.getSubCommand("").replace("\\", "/").strip("/ \t"); json input; std::cin >> input; - for(auto &next : json_path.split('/')) { - if(!next.empty()) - input = input[next]; - } + naive_json_access_path(input, json_path); //////////////////////////////////////////////////////////////////////