How to iterate through json objects with cpprest

2019-08-18 04:11发布

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条回答
够拽才男人
2楼-- · 2019-08-18 04:34

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;
    }
}
查看更多
登录 后发表回答