Search code examples
c++rapidjson

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

Solution

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