c++jsonrapidjson

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.. ?


Solution

  • 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;
    }