C++

How to parse JSON in C++

The intention of this tutorial is to understand the JSON data and how to parse JSON data in C++. We will discuss JSON data, Object, Array, JSON syntax, and then go through several working examples to understand the parsing mechanism of JSON data in C++.

What is JSON?

JSON is a light-weight text-based representation for storing and transferring structured data in an organized way. The JSON data is represented in the form of ordered lists and key-value pairs. JSON stands for JavaScript Object Notation. As the full name indicates, it is derived from JavaScript. However, JSON data is supported in most of the popular programming languages.

It is often used to transfer the data from the server to a web page. It is much easier and cleaner to represent the structured data in JSON than XML.

JSON Syntax Rule

Here are the JSON syntax rules:

  1. JSON Data should always be in the form of key-value pairs.
  2. JSON Data is separated by commas.
  3. A Curly brace is used to represent JSON Object.
  4. A square bracket is used to represent a JSON Array.

What is JSON Data?

The JSON data is represented in the form of key-value pairs. This is similar to a dictionary or hash in other programming languages.

“Name” : ”Drake”

This is an example of simple JSON data. The key here is “Name” and “Drake” is the corresponding value. The key, i.e., “Name” and the value, i.e., “Drake” are separated by a colon.

JSON File Extension

The JSON data is normally stored in the file with the extension of “.json”. For example, to store the employee’s data, you can simply name the file as ‘employee.json’. This would be a simple text file. You can then open this JSON file in any of your favorite text editors.

JSON Object

The JSON object is nothing but the JSON data enclosed within the curly braces. Here is a sample JSON object:

{
   “Name”: ”Drake”,
   “Employee ID”: “23547a”,
    “Phone”: “23547”,
    “Department”: “Finance”
 }

A JSON object can contain multiple JSON data. Each JSON data is separated by a comma. JSON data is represented as key-value pairs. The key, i.e., “Name” and the value, i.e., “Drake” are separated by a colon. In the above example, there are four key-value pairs. The first key is “Name”; “Drake” is the corresponding value for it. Similarly, “EmployeeID”, “Phone”, and “Department” are the other three keys.

JSON Array

A JSON array can contain several comma-separated JSON objects. The JSON array is enclosed within a square bracket. Let’s look at an example of a JSON array:

"Students":[
    {"firstName":"Sean", "lastName":"Brown"},
    {"firstName":"Drake", "lastName":"Williams"},
    {"firstName":"Tom", "lastName":"Miller"},
    {“firstName”:”Peter”, “lastName”: “Johnson”}
]

This is an example of a JSON array. Here, “Students” is enclosed with a square bracket, i.e., array, and it contains four JSON objects. Each of these objects is represented in the form of key-value pairs and is separated by a comma.

A Sample JSON File

Now, since we understood JSON data, JSON objects, JSON array, let’s look at an example of a JSON file:

{
  “firstName”: “Sean”,
  “lastName”: “Brown”,
  “Student ID”: 21453,
  “Department”: “Computer Sc.”,
  “Subjects”:[“Math”, “Phy”, “Chem”]
    }

Parsing Libraries in C++:

There is no native solution for parsing JSON data in C++. However, there are several libraries to parse JSON data in C++. In this article, we are going to look into the two most popular libraries to parse JSON data in C++. Here are the GitHub links for parsing JSON data:

  1. https://github.com/nlohmann/json
  2. https://github.com/Tencent/rapidjson/

You may want to download these libraries to be able to execute the examples shown below.

Examples

Now, we have a basic understanding of JSON data, objects, arrays, and available parsing libraries. Let’s now look at a couple of examples to parse JSON data in C++:

  • Example-1: Parse JSON in C++
  • Example-2: Parse and Serialize JSON in C++
  • Example-3: Parse JSON in C++

For Example-1 and Example-2, we are going to make use of the “nlohmann” library. In the case of Example-3, we will use the “RapidJSON” library.

Example-1: Parse JSON in C++

In this example program, we will demonstrate how to access values of JSON data in C++.

#include <iostream>
#include "json.hpp"

using json = nlohmann::json;

int main()
{
  // jdEmployees
  json jdEmployees =  {
    {"firstName","Sean"},
    {"lastName","Brown"},
    {"StudentID",21453},
    {"Department","Computer Sc."}};

   // Access the values
   std::string fName = jdEmployees.value("firstName", "oops");
   std::string lName = jdEmployees.value("lastName", "oops");
   int sID = jdEmployees.value("StudentID", 0);
   std::string dept = jdEmployees.value("Department", "oops");
   
   // Print the values
   std::cout << "First Name: " << fName << std::endl;
   std::cout << "Last Name: " << lName << std::endl;
   std::cout << "Student ID: " << sID << std::endl;
   std::cout << "Department: " << dept << std::endl;
           
   return 0;
}

Example-2: Parse and Serialize JSON in C++

In this example program, we are going to see how to parse and serialize JSON in C++. We are using “json::parse()” to parse the JSON data.

#include <iostream>
#include "json.hpp"
#include <iomanip>

using json = nlohmann::json;

int main()
{
    // Here is a JSON text
    char text[] = R"(
    {
        "Book": {
            "Width":  450,
            "Height": 30,
            "Title":  "Hello World",
            "isBiography": false,
            "NumOfCopies": 4,
            "LibraryIDs": [2319, 1406, 3854, 987]
        }
    }
    )"
;

    // Let's parse and serialize JSON
    json j_complete = json::parse(text);
    std::cout << std::setw(4) << j_complete << std::endl;
}

Example-3: Parse JSON in C++

Now, we will demonstrate how to parse JSON string using the RapidJSON library. RapidJSON was originally inspired by the RapidXML. In this example program, we are parsing a JSON string into DOM. We have declared “mydoc” of type “Document” and then using the “mydoc.parse()” method to parse the JSON string.

#include <iostream>
#include "rapidjson/writer.h"
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"

using namespace rapidjson;

int main()
{

  const char* json = "{"firstName":"Sean","lastName":"Brown","empId":21453,
  "
department":"Computer Sc."}";

  // Parse the JSON string into DOM
  Document mydoc;
  mydoc.Parse(json);

  // DOM to string
  StringBuffer buffer;
  Writer<StringBuffer> writer(buffer);

  mydoc.Accept(writer);

  // Print the output
  std::cout << buffer.GetString() << std::endl;

  return 0;
}

Conclusion

In this article, we have briefly discussed JSON data, object, array, and syntax. As we know, there is no native solution for JSON data parsing in C++; we have used two different libraries to parse JSON data in C++. We looked into three different examples to demonstrate the JSON data parsing mechanism in C++. As compared to the “nlohmann” library, the RapidJSON is small, fast, and memory-friendly.

About the author

Sukumar Paul

I am a passionate software engineer and blogger. I have done my Masters in Software Engineering from BITS PILANI University, India. I have very good experience in real-time software development and testing using C, C++, and Python. Follow me at thecloudstrap.com.