C++ nlohmann JSON 获取数组名称

C++ nlohmann JSON get name of array

本文关键字:数组 获取 nlohmann JSON C++      更新时间:2023-10-16

I have nlohmann json object:

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

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

但是我怎样才能得到数组名称呢?

您可以从 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;
}