【问题标题】:JSON using nlohmann::json jpointer for dynamic string and default valueJSON 使用 nlohmann::json jpointer 获取动态字符串和默认值
【发布时间】: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 &amp; ptr, const ValueType &amp; default_value ) 方法。

标签: c++ dynamic path jsonpointer


【解决方案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");
}

【讨论】:

  • 您的示例中 sub_path 的类型是什么?
  • nlohmann::json::json_pointer 或只是json::json_pointer(因为您在上面有using json = nlohmann::json 声明)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
  • 1970-01-01
  • 2018-01-27
  • 1970-01-01
  • 1970-01-01
  • 2016-09-30
  • 2021-07-13
相关资源
最近更新 更多