Open In App

How to Parse an Array of Objects in C++ Using RapidJson?

Last Updated : 06 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

RapidJSON is an open-source C++ library for parsing and serializing JSON (JavaScript Object Notation) data. It is designed to be fast and efficient, with a focus on simplicity and ease of use. It is widely used in a variety of applications and is known for its fast performance and low memory overhead. It is a popular choice for parsing and serializing JSON data in C++.

Features Of  RapidJSON:

  • A simple, easy-to-use API for parsing and serializing JSON data
  • Support for both SAX (Simple API for XML) and DOM (Document Object Model) parsing styles
  • Support for parsing JSON data from strings, streams, and files
  • Support for serializing JSON data to strings, streams, and files
  • Support for a wide range of basic data types, including numbers, strings, arrays, and objects
  • Support for reading and writing JSON data with or without formatting (e.g., indentation and whitespace)
  • Support for custom memory allocation and low-level memory manipulation

Installing  RapidJSON  library:

1. Download the latest version of RapidJSON from GitHub by visiting this link. You can either download the source code as a zip file or clone the repository using Git.

 

2. Extract the downloaded zip file or navigate to the root directory of the cloned repository.

3. RapidJSON is a header-only library, which means that you don’t need to build it or link it to your project. All you need to do is include the necessary header files in your C++ code. You can find the header files in the included directory of the RapidJSON repository.

4. To use RapidJSON in your C++ project, you need to include the necessary header files. You can do this by adding the following line to your C++ code:

5. If you want to use RapidJSON in multiple files in your project, you can add the include directory of the RapidJSON repository to the include path of your project. This way, you can include the RapidJSON header files in your code using double quotes (“) instead of angle brackets (<>).

Parsing JSON stringified data using RapidJSON library

In the following example, we first define a JSON string and parse it using the Parse() method of the rapidjson::Document class. Then, we check for parse errors using the HasParseError() method. If there are no parse errors, we can access the data in the JSON document using the [] operator and the Get*() methods of the rapidjson::Value class (e.g., GetString(), GetInt(), etc.).

C++




#include "lib/include/rapidjson/document.h"
/*
   The above include might vary depending on the
   location of the library you just downloaded
*/
 
#include <iostream>
 
int main()
{
    // Parse a JSON string, this can alternatively be read
    // from a file
    const char* json = "{\"name\":\"Raman\",\"age\":30,"
                       "\"city\":\"New Delhi\"}";
 
    rapidjson::Document doc;
    doc.Parse(json);
 
    // Check for parse errors
    if (doc.HasParseError()) {
        std::cerr << "Error parsing JSON: "
                  << doc.GetParseError() << std::endl;
        return 1;
    }
 
    // Access the JSON data
    std::cout << "Name: " << doc["name"].GetString()
              << std::endl;
    std::cout << "Age: " << doc["age"].GetInt()
              << std::endl;
    std::cout << "City: " << doc["city"].GetString()
              << std::endl;
 
    return 0;
}


Output:

Output Of The Above Code

Parsing an Array of Objects in C++ Using RapidJson

Let us break down this challenge into the steps mentioned below:

  1. Define a JSON string containing an array of objects and parse it using the Parse() method of the rapidjson::Document class.
  2. Check for parse errors using the HasParseError() method. If there are parse errors, handle them accordingly.
  3. Iterate over the array of objects using the Begin() and End() methods of the rapidjson::Value class. 
  4. For each object, access the data using the [] operator and the Get*() methods of the rapidjson::Value class (e.g., GetString(), GetInt(), etc.).

C++




#include "lib/include/rapidjson/document.h"
/*
   The above include might vary depending on the
   location of the library you just downloaded
*/
#include <iostream>
 
int main()
{
    // Parse a JSON string containing an array of objects
    const char* json
        = "[{\"name\":\"Chandrika\",\"age\":20,"
          "\"city\":\"Banglore\"}, "
          "{\"name\":\"Rhythm Shandlya\",\"age\":22,"
          "\"city\":\"Noida\"}]";
    rapidjson::Document doc;
    doc.Parse(json);
 
    // Check for parse errors
    if (doc.HasParseError()) {
        std::cerr << "Error parsing JSON: "
                  << doc.GetParseError() << std::endl;
        return 1;
    }
 
    // Iterate over the array of objects
    rapidjson::Value::ConstValueIterator itr;
 
    for (itr = doc.Begin(); itr != doc.End(); ++itr) {
        // Access the data in the object
        std::cout << "Name: "
                  << itr->GetObject()["name"].GetString()
                  << std::endl;
        std::cout << "Age: "
                  << itr->GetObject()["age"].GetInt()
                  << std::endl;
        std::cout << "City: "
                  << itr->GetObject()["city"].GetString()
                  << std::endl;
    }
 
    return 0;
}


Output:

Output Of The Above Code

RapidJSON provides many more features and options for parsing and manipulating JSON data. You can find more information and examples in the documentation and examples provided with the RapidJSON library.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads