Search code examples
c++jsonjsoncppnlohmann-json

nlohmann parsing a json file without knowing keys


I'm using nlohmann/json library to use json in cpp. I have a Json::Value object and I would like to go through my json data by exploring the keys without knowing them. I came across the documentation but only found the object["mySuperKey"] method to explore the datas which means to know the existing keys.

Can you please give me some tips ?

thanks.


Solution

  • Well, after creating a JSON Object, some types can be iterated. In the nlohmann::json implementation, you interact with two basic containers (json::object,json::array) both have keys that can be easily retrieved or printed.

    Here is a small example that implements a function to recursively (or not) traverse the JSON object and print the keys and value types.

    The code of the Example:

    #include <iostream>
    #include <vector>
    #include "json3.6.1.hpp"
    
    void printObjectkeys(const nlohmann::json& jsonObject, bool recursive, int ident) {
        if (jsonObject.is_object() || jsonObject.is_array()) {
            for (auto &it : jsonObject.items()) {
                std::cout << std::string(ident, ' ')
                          << it.key() << " -> "
                          << it.value().type_name() << std::endl;
                if (recursive && (it.value().is_object() || it.value().is_array()))
                    printObjectkeys(it.value(), recursive, ident + 4);
            } 
        }
    }
    
    int main()
    {
        //Create the JSON object:
        nlohmann::json jsonObject = R"(
            {
                "name"    : "XYZ",
                "active"  : true,
                "id"      : "4509237",
                "origin"  : null,
                "user"    : { "uname" : "bob", "uhight" : 1.84 },
                "Tags"    :[
                    {"tag": "Default", "id": 71},
                    {"tag": "MC16",    "id": 21},
                    {"tag": "Default", "id": 11},
                    {"tag": "MC18",    "id": 10}
                ],
                "Type"    : "TxnData"
            }
        )"_json;
        std::cout << std::endl << std::endl << "Read Object key, not recursive :" << std::endl;
        printObjectkeys(jsonObject, false, 1);  
        std::cout << std::endl << std::endl << "Read Object key, recursive :" << std::endl;
        printObjectkeys(jsonObject, true, 1);
    
        return 0;
    }