gpt4 book ai didi

c++ - 如何使用 cpprest 遍历 json 对象

转载 作者:行者123 更新时间:2023-11-27 23:46:33 28 4
gpt4 key购买 nike

我有一个保存 json 数据的“jvalue”变量:

{
"data": [
{
"_id": 123,
"name": "Name 1"
},
{
"_id": 124,
"name": "Name 2"
}
],
"success": true
}

这是我试过的代码:

auto data = jvalue.at(U("data")).at(0);
auto dataObj = data.as_object();

for (auto iterInner = dataObj.cbegin(); iterInner != dataObj.cend(); ++iterInner)
{
auto &propertyName = iterInner->first;
auto &propertyValue = iterInner->second;

std::wcout << "Property: " << propertyName << ", Value: " << propertyValue << std::endl;
}

但它只显示第一组数据:

Property: _id, Value: 123
Property: name, Value: "Name 1"

我知道我在这里遗漏了一些东西,但我不会想到这个想法。可能类似于双 for 循环。

任何人都可以分享这个想法。谢谢。

最佳答案

现在你只遍历对象的属性,你也必须遍历数组元素:

auto DataArray = jvalue.at(U("data")).as_array();

for (int i = 0; i< DataArray.size(); i++)
{
auto data = DataArray[i];
auto dataObj = data.as_object();

for (auto iterInner = dataObj.cbegin(); iterInner != dataObj.cend(); ++iterInner)
{
auto &propertyName = iterInner->first;
auto &propertyValue = iterInner->second;

std::wcout << "Property: " << propertyName << ", Value: " <<
propertyValue << std::endl;
}
}

或者使用迭代器遍历数组:

auto DataArray = jvalue.at(U("data")).as_array();

for (auto Iter = DataArray.begin(); Iter != DataArray.end(); ++Iter)
{
auto& data = *Iter;
auto dataObj = data.as_object();

for (auto iterInner = dataObj.cbegin(); iterInner != dataObj.cend(); ++iterInner)
{
auto &propertyName = iterInner->first;
auto &propertyValue = iterInner->second;

std::wcout << "Property: " << propertyName << ", Value: " <<
propertyValue << std::endl;
}
}

关于c++ - 如何使用 cpprest 遍历 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50096040/

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