How to iterate through json objects with cpprest

ぐ巨炮叔叔 提交于 2019-12-24 23:45:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!