The Wayback Machine - https://web.archive.org/web/20240829154307/https://www.geeksforgeeks.org/how-to-parse-an-array-of-objects-in-cpp-using-rapidjson/
Open In App

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

Last Updated : 06 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Similar Reads

How to Read and Parse Json File with RapidJson?
RapidJSON is a high-performance JSON library for C++. It provides a fast and easy-to-use interface for parsing and generating JSON. It is small but complete. It supports both SAX and DOM style API. Also, it is self-contained and header-only. It does not depend on external libraries such as BOOST. It even does not depend on STL. Here is an example o
5 min read
RapidJSON - File Read/Write in C++
RapidJSON is a C++ library for parsing and generating JSON (JavaScript Object Notation) data. It is designed for high performance and can handle very large JSON documents. RapidJSON supports both reading and writing JSON data, as well as validation and manipulation of JSON objects. It also includes support for parsing and generating JSON in a strea
6 min read
How to initialize Array of objects with parameterized constructors in C++
Array of Objects: When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects. Syntax: ClassName ObjectName[number of objects]; Different methods to initialize the Array of objects with parameterized constructors:
6 min read
Array of Objects in C++ with Examples
An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array.  They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in
5 min read
Count the number of objects using Static member function
Prerequisite : Static variables , Static Functions Write a program to design a class having static member function named showcount() which has the property of displaying the number of objects created of the class. Explanation: In this program we are simply explaining the approach of static member function. We can define class members and member fun
2 min read
Comparing String objects using Relational Operators in C++
If strings are compared using relational operators then, their characters are compared lexicographically according to the current character traits, means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered. Parameters : Two Strings required t
2 min read
How to Avoid Memory Leaks When Using a Vector of Pointers to Dynamically Allocated Objects in C++?
In C++, managing memory properly is very important to avoid memory leaks, especially when working with dynamically allocated objects. When using a std::vector of pointers to dynamically allocated objects, we need to ensure that all allocated memory is properly deallocated. In this article, we will learn different methods to avoid memory leaks in su
6 min read
Static Objects in C++
Prerequisite: Static Keyword in C++ An object becomes static when a static keyword is used in its declaration. Static objects are initialized only once and live until the program terminates. They are allocated storage in the data segment or BSS segment of the memory. C++ supports two types of static objects: Local Static ObjectsGlobal Static Object
3 min read
Introduction to Complex Objects and Composition
An object is a basic unit of Object-Oriented Programming and represents the real-life entities. Complex objects are the objects that are built from smaller or a collection of objects. For example, a mobile phone is made up of various objects like a camera, battery, screen, sensors, etc. In this article, we will understand the use and implementation
4 min read
Anonymous Objects in C++
Prerequisite: Class and Objects in C++ An Object is an instance of a Class. A class has no memory allocated it is just like a blueprint, but when it is instantiated (i.e. an object is created) memory is allocated just like the real-world instance of that blueprint. An object that does not have a reference variable is known as an anonymous object. T
4 min read
Creating a Vector of Class Objects in C++
Prerequisites: Object Oriented Programming in C++Vector in C++ Class is a user-defined data type that can be accessed by creating objects or instances of that class. A vector is a type of container which can store elements of a similar type. Vector of Class The vector of class objects is an example of a custom vector made where we can store multipl
3 min read
Reference to Dynamic Objects in C++
In C++, the objects can be created at run-time. C++ supports two operators new and delete to perform memory allocation and de-allocation. These types of objects are called dynamic objects. The new operator is used to create objects dynamically and the delete operator is used to delete objects dynamically. The dynamic objects can be created with the
3 min read
How to make a C++ class whose objects can only be dynamically allocated?
The problem is to create a class such that the non-dynamic allocation of object causes compiler error. For example, create a class 'Test' with following rules. C/C++ Code Test t1; // Should generate compiler error Test *t3 = new Test; // Should work fine The idea is to create a private destructor in the class. When we make a private destructor, the
2 min read
How to Restrict Dynamic Allocation of Objects in C++?
C++ programming language allows both auto(or stack-allocated) and dynamically allocated objects. In Java &amp; C#, all objects must be dynamically allocated using new. C++ supports stack-allocated objects for the reason of runtime efficiency. Stack-based objects are implicitly managed by the C++ compiler. They are destroyed when they go out of scop
2 min read
Read/Write Class Objects from/to File in C++
Given a file "Input.txt" in which every line has values same as instance variables of a class. Read the values into the class's object and do necessary operations.Theory : The data transfer is usually done using '&gt;&gt;' and &lt;&lt;' operators. But if you have a class with 4 data members and want to write all 4 data members from its object direc
3 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
What’s difference between “array” and “&amp;array” for “int array[5]” ?
If someone has defined an array such as “int array[5]”, what’s the meaning of “array” or “&amp;array”? Are they both same or are they different? You might be tempted to think that they both would point to the very first element of the array i.e. they both will have same address. Let us find out! To check this, the very first thing that comes to min
4 min read
array::front() and array::back() in C++ STL
Array classes are generally more efficient, light-weight, and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::front() This function is used to reference the first element of the array container. This function can be used to fetch the first element of an array. Synt
3 min read
array::fill() and array::swap() in C++ STL
Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::fill() This function is used to set a common value for all the elements of the array container. Syntax : arrayname.fill(value) Parameters : The value to be
3 min read
array::begin() and array::end() in C++ STL
Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::begin() begin() function is used to return an iterator pointing to the first element of the array container. begin() function returns a bidirectional iterat
3 min read
array::cbegin() and array::cend() in C++ STL
array::cbegin() is a built-in function in C++ STL which returns a const_iterator pointing to the first element in the array. It cannot be used to modify the element in the array which is possible using array::begin(). Syntax: array_name.cbegin() Parameters: The function does not accept any parameters. Return Value: The function returns a const_iter
2 min read
array::rbegin() and array::rend() in C++ STL
array::rbegin() is a built-in function in C++ STL which returns a reverse iterator pointing to the last element in the container. Syntax:array_name.rbegin()Parameters: The function does not accept any parameter. Return value: The function returns a reverse iterator pointing to the last element in the container. Program to demonstrate the array::rbe
2 min read
Maximum array elements that can be removed along with its adjacent values to empty given array
Given an array arr[] of size N. In each operation, pick an array element X and remove all array elements in the range [X - 1, X + 1]. The task is to find the maximum number of steps required such that no coins left in the array. Examples: Input: coins [] = {5, 1, 3, 2, 6, 7, 4} Output: 4 Explanation: Picking the coin coins[1] modifies the array arr
7 min read
Mean of given array after removal of K percent of smallest and largest array elements
Given an array arr[] and an integer K, the task is to remove K % percent array elements from the smallest and largest array elements and calculate the mean of the remaining array. Examples: Input: arr[] = {6, 2, 7, 5, 1, 2, 0, 3, 10, 2, 5, 0, 5, 5, 0, 8, 7, 6, 8, 0}, K = 5Output: 4.00000Explanation:There are 20 elements in the array. Therefore, 5%
6 min read
Generate an array consisting of most frequent greater elements present on the right side of each array element
Given an array A[] of size N, the task is to generate an array B[] based on the following conditions: For every array element A[i], find the most frequent element greater than A[i] present on the right of A[i]. Insert that element into B[].If more than one such element is present on the right, choose the element having the smallest value.If no elem
9 min read
Count of ways to convert given Array such that array maximum is not present in the first half
Given an array arr[] of even size N. The task is to count the number of ways of converting arr[] such that the first half of the array does not contain the maximum number. Examples: Input: arr[] = {2, 2, 5, 2, 2, 2}Output: 3Explanation: Following are the ways where the maximum element 5 is not present in the first half of the array.[2, 2, 2, 5, 2,
6 min read
Array of Structures vs Array within a Structure in C++
In C++, an array of structure and an array within structure are used frequently used for data storage. Although they sound similar, they work pretty differently from each other. In this article, we will discuss the key differences between an array of structures and an array within structures and clarify the confusion. Array of Structures in C++An a
4 min read
Pointer to an Array | Array Pointer
Prerequisite: Pointers Introduction  Consider the following program:  [GFGTABS] C #include&lt;stdio.h&gt; int main() { int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr; printf(&quot;%p\n&quot;, ptr); return 0; } [/GFGTABS]In the above program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer
9 min read
Sum of array using pointer arithmetic
Given an array, write a program to find the sum of array using pointers arithmetic. In this program we make use of * operator . The * (asterisk) operator denotes the value of variable. The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer . sum() functi
2 min read
Iterating over all possible combinations in an Array using Bits
There arise several situations while solving a problem where we need to iterate over all possible combinations of an array. In this article, we will discuss the method of using bits to do so.For the purpose of explaining, consider the following question: Given an array b[] = {2, 1, 4}. The task is to check if there exists any combination of element
7 min read
Article Tags :
Practice Tags :