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;
}
First of all, you can just use
::value
with ajson_pointer
. Second, you can use the/
operator to construct new json_pointers. Thus, yourmain
function can do the following: