JSON using nlohmann::json jpointer for dynamic string and default value

2k views Asked by At

In nlohmann::json library if a key is not found there is a provision to return the default value like this

j.value("/Parent/child"_json_pointer, 100);

here 100 will be returned if "/Parent/child" is not found But if the "/Parent/child" is dynamic like an array for example

eg. /Parent/child/array/0/key
/Parent/child/array/1/key
then I need to create json pointer like following

nlohmann::json::json_pointer jptr(str) //str = "/Parent/child/array/0/key"

How to get the default value behavour with "jptr". Is there any other approch.

Adding sample code.

Json File

{
        "GNBDUFunction": {
                "gnbLoggingConfig": [{
                                "moduleId": "OAMAG",
                                "logLevel": "TRC"
                        },
                        {
                                "moduleId": "FSPKT",
                                "logLevel": "TRC"
                        }
                ],
                "ngpLoggingConfig": [{
                                "moduleId": "MEM",
                                "logLevel": "FATAL"
                        },
                        {
                                "moduleId": "BUF",
                                "logLevel": "FATAL"
                        },
                        {
                                "moduleId": "PERF",
                                "logLevel": "FATAL"
                        }
                ]
        }
}

Code

#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>
#include <string>
using namespace std;
using json = nlohmann::json;

void parse(json& j,std::string path) {

nlohmann::json::json_pointer jptr(path);
json &child = j.at(jptr);
std::string moduleId = child.at("moduleId");
std::string loglvl = child.at("logLevel","FATAL");//How to get with default ??
}

int main()
{
 std::ifstream name("test.json");
 json j = nlohmann::json::parse(name);
 std::string path ="GNBDUFunction/gnbLoggingConfig";
 int count  = j.at("/GNBDUFunction/gnbLoggingConfig"_json_pointer).size();
 for (int i = 0 ; i < count ;++i)
 {
     const std::string sub_path = "/" + path + "/" +std::to_string(i);
     parse(j,sub_path);
 }

return 0;
}
1

There are 1 answers

2
Botje On BEST ANSWER

First of all, you can just use ::value with a json_pointer. Second, you can use the / operator to construct new json_pointers. Thus, your main function can do the following:

json j = nlohmann::json::parse(name);
auto root = "/GNBDUFunction/gnbLoggingConfig"_json_pointer;
size_t count  = j.at(root).size();
for (size_t i = 0 ; i < count ; ++i) {
    auto sub_path = root / i / "moduleId" / "logLevel";
    std::string loglvl = j.value(sub_path, "FATAL");
}