问题
I have a "jvalue" variable that holds a json data:
{
"data": [
{
"_id": 123,
"name": "Name 1"
},
{
"_id": 124,
"name": "Name 2"
}
],
"success": true
}
This is my code that i tried:
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;
}
But it displays the first set of data only:
Property: _id, Value: 123
Property: name, Value: "Name 1"
I know I'm missing something here, but the idea won't pop up to my mind. Maybe something like double for loop.
Can anybody share an idea to this. Thank you.
回答1:
Now you are iterating only over object's properties, you have to iterate over array elements too:
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;
}
}
Or use iterators to iterate over array:
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;
}
}
来源:https://stackoverflow.com/questions/50096040/how-to-iterate-through-json-objects-with-cpprest