/* This program uses an iterator to enumerate the keys inside a JSON object. For each key, it prints: - The key and val, if the val is a number or string. - The key and val size if the val is an object or array. */ #include "nlohmann/json.hpp" #include using namespace std; using nlohmann::json; int main() { json js; json::const_iterator jit; /* Read the json from standard input. */ cin >> js; /* If it's not an object, print an error message and exit. */ if (!js.is_object()) { cout << "Not a JSON object: " << js << endl; return 0; } /* Otherwise, run through the keys with an iterator and print them. */ for (jit = js.begin(); jit != js.end(); jit++) { printf("Key: %-10s ", jit.key().c_str()); if (jit.value().is_string() || jit.value().is_number()) { cout << "Value: " << jit.value() << endl; } else if (jit.value().is_object() || jit.value().is_array()) { cout << "Size: " << jit.value().size() << endl; } else { cout << "Unknown value type.\n"; } } return 0; }