在 nlohmann::json 库中,如果未找到密钥,则规定返回默认值,如下所示
j.value("/Parent/child"_json_pointer, 100);
如果找不到“/Parent/child”,则此处将返回 100 但是如果“/Parent/child”是动态的,例如数组
例如。/Parent/child/array/0/key
/Parent/child/array/1/key
然后我需要创建 json 指针,如下所示
nlohmann::json::json_pointer jptr(str) //str = "/Parent/child/array/0/key"
如何使用“jptr”获取默认值行为。有没有其他方法。
添加示例代码。
json文件
{
"GNBDUFunction": {
"gnbLoggingConfig": [{
"moduleId": "OAMAG",
"logLevel": "TRC"
},
{
"moduleId": "FSPKT",
"logLevel": "TRC"
}
],
"ngpLoggingConfig": [{
"moduleId": "MEM",
"logLevel": "FATAL"
},
{
"moduleId": "BUF",
"logLevel": "FATAL"
},
{
"moduleId": "PERF",
"logLevel": "FATAL"
}
]
}
}
代码
#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;
}