0

在 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;
}
4

1 回答 1

1

首先,您可以只::value使用json_pointer. 其次,您可以使用/运算符构造新的 json_pointers。因此,您的main函数可以执行以下操作:

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");
}

于 2020-05-05T07:28:09.340 回答