1

我有 nlohmann json 对象:

json uuid = R"(
                 {
                    "uuid": ["aaa","bbb","ccc"]
                 }
              )"_json;

我可以毫无问题地获取数组中的值: str = uuid["uuid"][0];

但是我怎样才能自己获得数组名称?

4

1 回答 1

1

您可以从 json 对象获取底层映射,该对象为您提供数组名称和数组。如果您只想遍历这些项目也很容易。

#include <iostream>
#include <json.hpp>

using json = nlohmann::json;

int main()
{
    json uuid = R"(
                 {
                    "uuid": ["aaa","bbb","ccc"],
                    "uuie": ["aaa","bbb","ccc"],
                    "uuif": ["aaa","bbb","ccc"]
                 }
              )"_json;

    if (uuid.is_object())
    {
        auto obj = uuid.get<json::object_t>();
        for (auto& kvp : obj)
        {
            std::cout << kvp.first << ":" << kvp.second << "\n";
        }
    }

    for (auto& item : uuid)
    {
        std::cout << item << "\n";
    }

    return 0;
}
于 2018-06-22T05:14:00.173 回答