gpt4 book ai didi

C++ nlohmann JSON 获取数组名称

转载 作者:行者123 更新时间:2023-11-30 04:59:58 36 4
gpt4 key购买 nike

我有 nlohmann json 对象:

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

关于C++ nlohmann JSON 获取数组名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50980563/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com