Search code examples
c++jsonnlohmann-json

How to parse json with nlohmann lib?


I use this lib for json parsing https://github.com/nlohmann/json

I need to pars this json file

{
  "emulators": [
    {
      "general_info": {
        "dev_id": "0123456789",
        "model": "my_model",
        "model_full": "my_full_model",
        "serial_num": "my_serial_num"
      }
    }
  ]
}

there is how I am trying to do it

void EmulatorCameraConfigParser::GetEmulatorContextObjFrom(std::string path_to_configuration_json, std::vector<emulator_context::EmulatorContextObj> * out_arr)
{
    json jf = Utils::get_json_data(path_to_configuration_json);

    if (jf == nullptr)
    {
        //TODO print - "Configuration json file for TV_CamFromFiles is null";
    }
    else
    {
        try
        {
            for (auto& elem : jf[EMULATORS])
            {
                emulator_context::EmulatorContextObj tmp;

                tmp.m_general_info = &get_general_info(elem[GENERAL_INFO]);
                out_arr->push_back(tmp);
            }
        }
        catch (std::exception& ex)
        {
            //TODO print error
            std::string errMsg = "Exeption during parsing configuration json file for TV_CamFromFiles :: ";
            errMsg += ex.what();
        }
    }
}
emulator_context::GeneralInfo EmulatorCameraConfigParser::get_general_info(const json& json)
{
    emulator_context::GeneralInfo generalInfo;

    try
    {
        if (json != nullptr)
        {
            generalInfo.m_dev_id = json.at(DEV_ID).get<std::string>();
            generalInfo.m_serial_num = json.at(SERIAL_NUM).get<int>();
        }
    }
    catch (std::exception& ex)
    {
        //TODO print this error
        std::string errMsg = "Exeption during parsing configuration json file for TV_CamFromFiles :: ";
        errMsg += ex.what();
    }

    return generalInfo;
}

But as a result I get nothing, so I am almost sure that problem is here tmp.m_general_info = &get_general_info(elem[GENERAL_INFO]);

I think that in order to get block general_info I need to use other way, but which one?


Solution

  • Loading json from a file is simpler than that.

    #include <nlohmann/json.hpp>
    
    #include <iostream>
    #include <sstream>
    #include <string>
    
    using json = nlohmann::json;
    
    int main() {
        // open the json file - here replaced with a std::istringstream containing the json data
    
        std::istringstream file(R"json({
      "emulators": [
        {
          "general_info": {
            "dev_id": "0123456789",
            "model": "my_model",
            "model_full": "my_full_model",
            "serial_num": "my_serial_num"
          }
        }
      ]
    })json");
    
        // declare your json object and stream from the file
        json j;
        file >> j;
    
        // the file is now fully parsed
    
        // access fields
        for(json& o : j["emulators"]) {
            json& gi = o["general_info"];
            std::cout << gi["dev_id"] << '\n';
            std::cout << gi["model"] << '\n';
            std::cout << gi["model_full"] << '\n';
            std::cout << gi["serial_num"] << '\n';
        }
    }
    

    Output

    "0123456789"
    "my_model"
    "my_full_model"
    "my_serial_num"
    

    You can also add your own serializer support:

    #include <nlohmann/json.hpp>
    
    #include <iostream>
    #include <sstream>
    #include <string>
    
    using json = nlohmann::json;
    
    struct general_info {
        std::string dev_id;
        std::string model;
        std::string model_full;
        std::string serial_num;
    };
    
    // conversion functions for your general_info
    void to_json(json& j, const general_info& gi) {
        j = json{{"dev_id", gi.dev_id},
                 {"model", gi.model},
                 {"model_full", gi.model_full},
                 {"serial_num", gi.serial_num}};
    }
    
    void from_json(const json& j, general_info& gi) {
        j.at("dev_id").get_to(gi.dev_id);
        j.at("model").get_to(gi.model);
        j.at("model_full").get_to(gi.model_full);
        j.at("serial_num").get_to(gi.serial_num);
    }
    
    int main() {
        std::istringstream file(R"json({
      "emulators": [
        {
          "general_info": {
            "dev_id": "0123456789",
            "model": "my_model",
            "model_full": "my_full_model",
            "serial_num": "my_serial_num"
          }
        }
      ]
    })json");
    
        // declare your json object and stream from the file
        json j;
        file >> j;
    
        // convert a json array of "general_info" to a std::vector<general_info>
    
        json& arr = j["emulators"];
    
        std::vector<general_info> gis;
    
        std::for_each(arr.begin(), arr.end(), [&gis](const json& o) {
            if(auto it = o.find("general_info"); it != o.end()) {
                gis.push_back(it->get<general_info>());
            }
        });
    
        for(general_info& gi : gis) {
            std::cout << gi.dev_id << '\n';
            std::cout << gi.model << '\n';
            std::cout << gi.model_full << '\n';
            std::cout << gi.serial_num << '\n';
        }
    }