Venelin
Venelin

Reputation: 3306

C++/rapidjson - unable to iterate over array of objects

I have the following json:

{
    "data": {
        "10": {
            "id": 11,
            "accountId": 11,
            "productId": 2,
            "variantId": 0,
            "paymentMethod": "PayPal",
            "amount": "9.99",
            "status": "confirmed",
            "created_at": "2019-12-02T21:55:30.000000Z",
            "updated_at": "2019-12-02T21:56:57.000000Z"
        },
        "12": {
            "id": 14,
            "accountId": 69,
            "productId": 3,
            "variantId": 0,
            "paymentMethod": "PayPal",
            "amount": "19.99",
            "status": "confirmed",
            "created_at": "2019-12-05T09:09:21.000000Z",
            "updated_at": "2019-12-05T09:14:09.000000Z"
        },
       }
}

Here is how I parse it:

// parse JSON response
rapidjson::Document parsed_response;
parsed_response.Parse(readBuffer.c_str());

const rapidjson::Value& data = parsed_response[ "data" ];
for ( rapidjson::Value::ConstMemberIterator iterator = data.MemberBegin(); iterator != data.MemberEnd(); ++iterator )
{
    std::cout << iterator->name.GetString() << std::endl;
}

This gives following output:

10
12

I am unable unfortunately to get into objects 10 and 12 and get the accountId or any other member of objects 10 and 12.

How can I get inside these objects and retrieve any data there like accountId, productId, variantId etc.. ?

Upvotes: 0

Views: 489

Answers (2)

Caleth
Caleth

Reputation: 63152

iterator->name refers to the bit before the : in the json, to get at the other side you need iterator->value.

for ( auto & data : parsed_response[ "data" ].GetObject() )
{
    std::cout << data.name.GetString()
              << data.value["accountId"].GetString()
              << data.value["productId"].GetString()
              << data.value["variantId"].GetString()
              << std::endl;
}

Upvotes: 1

Andrei Vukolov
Andrei Vukolov

Reputation: 586

You are iterating over only the first level of the array. You should use IsObject() function to determine if the field itself contains an object. After that, as it is already described here, you can use GetObject() function to access the internal fields of the nested JSON object using the nested loop:

if(iterator->IsObject())
{
   for (auto& nested : iterator->GetObject()){ ... }
}

Upvotes: 0

Related Questions