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

  c++, json

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
}

Source: Windows Questions C++

LEAVE A COMMENT