【问题标题】:C++ nlohmann/json how to use runtime provided json_pointers to read json valuesC++ nlohmann/json 如何使用运行时提供的 json_pointers 来读取 json 值
【发布时间】:2016-06-27 23:04:51
【问题描述】:

我正在使用现代 C++ (https://github.com/nlohmann/json) 的 json 解析器 Json。我知道我可以使用 JSON_Pointer 获取 JSON 值的值:

auto v1 = j["/a/b/c"_json_pointer];

但是,如果 JSON 指针是在运行时定义的(传递到我的函数中),我将如何获取值?

std:string s1 = "/a/b/c";
auto v1 = j[s1]; // doesn't work

您不能将“json_pointer”附加到 std::string 赋值或 s1 变量。是否有将 std::string 转换为 json_pointer 的函数?调用者对 json 一无所知,无法访问“json.hpp”标头。我也试过了

std::string s1 = "/a/b/c";
json_pointer p1(s1);

但是“json_pointer”类是未定义的。除了这个问题,这是一个很棒的库,可以做我需要的一切。 TIA。

【问题讨论】:

    标签: c++ json nlohmann-json


    【解决方案1】:

    看源码:

    inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t)
    {
        return nlohmann::json::json_pointer(s);
    }
    

    如果 json_pointer 未定义,那么您没有使用正确的命名空间。试试

    using nlohmann::json::json_pointer;
    std::string s1 = "/a/b/c";
    json_pointer p1(s1);
    

    【讨论】:

    • 我发誓这是我尝试的第一件事,但不会编译。刚刚再试一次,它就像一个魅力。感谢您的快速和非评判性的回应。
    • 没问题。下次尝试构建一个MCVE。当我遇到问题时,有一半的时间我只是通过首先构建一个来解决它。
    猜你喜欢
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多