Home > Blockchain >  Json nlohmann : generic function that return a value that is deep of several keys
Json nlohmann : generic function that return a value that is deep of several keys

Time:09-24

I need a function to get the content of a value which need more than one key to access of it. In the example bellow, I successfully get value of file_content["happy"] but how to write my function get() to accept more than one key for example access to file_content["answer"]["everything"] ?

Note that it could be more than 2 keys.

#include <nlohmann/json.hpp>
#include <string>
#include <fstream>
#include <iostream>


using json = nlohmann::json;

class My_config {
    public:
    My_config(const std::string config_path) {
        // Open and read Configuration file
        std::ifstream ifs(config_path);
        if (ifs.is_open()) {
            file_content = json::parse(ifs);
            ifs.close();
        }
    }

    json get(std::string key) {
        return file_content[key];
    }

    private:
    json file_content;
};

int main() {
    auto my_conf = My_config("../test.json");

    std::cout << "Get happy : " << my_conf.get("happy") << std::endl;
    
    // How to get ["answer"]["everything"] ?
    std::cout << "Get [answer][everything] : " << my_conf.get("answer", "everything") << std::endl;

    return 0;
}

test.json :

{
    "answer": {
        "everything": 42
    },
    "happy": true
}

CodePudding user response:

Using a loop should do the job:

json get(std::initializer_list<std::string> keys) {
    json data = file_content;
    for (auto& key : keys) {
        data = data[key];
    }
    return data;
}

requires extra {} at call site:

my_conf.get({"answer", "everything"});
  • Related