Noe Cano
Noe Cano

Reputation: 515

Access fields of a JSON array using RapidJSON in C++

I am new using the RapidJSON library and I want to know how I can access specific elements within an array in JSON format, this is the JSON:

{
  "products": [
    {
      "id_product": 1,
      "product_name": "Beer",
      "product_price": 120.00
    },
    {
      "id_product": 2,
      "product_name": "Pizza",
      "product_price": 20.00
    }
  ]
}

I have this part of the code to make:

Document json_value;
json_value.Parse(json_message); //Above Json

if(!json_value.IsObject())
{
    //ERROR
}

if(json_value.HasMember("products"))
{       
    const Value& a = json_value["products"];

    if(a.IsArray())
    {
        for (SizeType i = 0; i < a.Size(); i++)
        {
            //Here i dont know how to access the elements of the array elements, but i need something like this:
            int element_id = 1; //id_product = 1
            string element_name = "Beer"; // product_name = "Beer"
            float element_price = 120.00; //prodcut_price = 120.00
        }
    }
}

Upvotes: 2

Views: 4333

Answers (3)

rudedude
rudedude

Reputation: 723

You can access the elements of the object using operator[]().

for (SizeType i = 0; i < a.Size(); i++)
{
    if (a[i].IsObject()) {
        int element_id = a[i]["id_product"].GetInt();
        string element_name = a[i]["product_name"].GetString();
        double element_price = a[i]["product_price"].GetDouble();
    }
}

Please note that you might want to add checks for the type and existence of the member if your JSON is not always consistent.

Upvotes: 3

Joseph D.
Joseph D.

Reputation: 12174

Since for each "product" in products is an object, you can also iterate each key,value pair like this:

const Value& products = json_value["products"];
for (auto& product: products) {  // products is type Array
   for (auto& prod : product.GetObject()) {
      std::cout << prod.name  // similar to map->first
                              // i.e "id_product", "product_name"
                << prod.value // similar to map->second
                              // i.e 2, "Pizza"
                << std::endl;
   }
}

Upvotes: 2

Matt Hellige
Matt Hellige

Reputation: 118

I believe you can just call operator[]() with an unsigned int, if the value is an array. The tutorial appears to confirm this:

const Value& a = document["a"];
assert(a.IsArray());
for (SizeType i = 0; i < a.Size(); i++) // Uses SizeType instead of size_t
        printf("a[%d] = %d\n", i, a[i].GetInt());

You can also get iterators using MemberBegin() and MemberEnd().

Upvotes: 0

Related Questions