0

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.

pipou
  • 270
  • 3
  • 15
  • You would iterate all it's keys using it's `begin()` and `end()` methods. – SergeyA Sep 23 '19 at 18:36
  • See https://stackoverflow.com/questions/55431552/how-to-iterate-over-a-json-in-json-for-modern-c/55466160#55466160 – Daniel Sep 27 '19 at 20:57

1 Answers1

2

Well after creating a json Object - there are types that can be iterated. in this nlohmann::json implementation you interact with to basic containers (json::object,json::array) both has 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;
}
Shlomi Hassid
  • 6,500
  • 3
  • 27
  • 48