【发布时间】:2020-05-05 07:17:37
【问题描述】:
在 nlohmann::json 库中,如果未找到密钥,则提供这样的返回默认值的规定
j.value("/Parent/child"_json_pointer, 100);
如果没有找到“/Parent/child”,这里将返回 100 但是如果“/Parent/child”像数组一样是动态的,例如
例如。 /父/子/数组/0/key
/父/子/数组/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;
}
【问题讨论】:
-
你可以只传递一个
json_pointer作为第一个参数,有一个json::value(const json_pointer & ptr, const ValueType & default_value )方法。
标签: c++ dynamic path jsonpointer