Parse JSON Data in C++ Using nlohmann/json Library

JavaScript Object Notation is a format for data interchange that is easily understandable and writable by both humans and machines, and it is lightweight. The nlohmann/json library in C++ allows us to parse and handle JSON data effectively.

What is JSON

JSON is the format widely used for data exchange and representation. It is based on key-value pairs and supports data types such as strings, numbers, booleans, arrays and objects. It is commonly used in web applications, API and configuration files. JSON is used due to its simplicity and human-readable format.  Examples of some data types in JSON are as follows. The string is a list of characters shown in quotes, i.e., “Hello, World.” The number is an integer or float, i.e., 20 (integer), 2.02(float). An array is a set of ordered values shown in square brackets, i.e., [“Aryan”, “Raju”]. Boolean is expressing true or false value.

What is Parsing JSON Data in C++

The process of reading and interpreting JSON-formatted text to extract meaningful information/insights is known as Parsing JSON data in C++. It involves converting strings into structured data that C++ programs can manipulate. We can parse JSON from files, and strings and access its elements using key-value pairs, for this nlohmann/json library is used. JSON Parsing is important for Data interchange, Logging and Monitoring, etc.

nlohmann/json library

The simple way to work with JSON in C++ is provided by the nlohmann/json library. You can only need to include its header file in your project without additional dependencies. We can do easy parsing of JSON data, and also support STL containers like ‘vector’ and ‘map’. The nlohmann/json is compatible with modern C++ as well.

How to install for Windows

we can install nlohmann/json using vcpkg on Windows by the command to command prompt

vcpkg install nlohmann-json
How to install for Ubuntu

we can install nlohmann/json using the following command to the terminal of your Ubuntu system, but before you install nlohmann/json, good practice to update the packet index.

sudo apt-get install nolhmann-json3-dev

Example of Parsing JSON Data  in C++

In this example, we have a JSON file named jsonfile.json and our C++ code file main.cpp

JSON File

jsonfile.json
{
    "name": "Arshi",
    "mobile_no": 123456789,
    "university": "SPPU",
    "is_fresher": true,
    "skills": ["C++", "Python", "AI", "Cloud Computing"]
}

C++ Code

main.cpp
#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>
using namespace std; 
using json = nlohmann::json;  

int main() {
    
    ifstream file("jsonfile.json");
    if (!file) {
        cout << "ERROR : File not Opened, Error while opening the file!" << endl;
        return 1;
    }
    json jsn;
    file >> jsn;
    file.close();
    cout<<"-|- Parsing done -|-"<<endl;

    string name = jsn["name"];
    long long mobile_no = jsn["mobile_no"];
    string university_or_college_name = jsn["university"];
    bool is_student = jsn["is_fresher"];

    cout << "--Display Old data:" << endl;
    
    cout<< "Name: " << name <<endl;
    cout<< "Mobile Number: " << mobile_no <<endl; 
    cout<< "University or College Name: "<< university_or_college_name<<endl;
    if (is_student) {
        cout<< "Is Fresher: Yes" << endl;
    } else {
        cout<< "Is Fresher: No" << endl;
    }
    cout<<"Skills: ";
    for(int i = 0; i < jsn["skills"].size(); i++) {
        cout << jsn["skills"][i] << " ";
    }
    
    jsn["name"] = "Asmita";
    jsn["mobile_no"] = 9876543210;
    jsn["university"] = "RSU";
    jsn["is_fresher"] = false;

    jsn["skills"].push_back("ML");
    if(!jsn["skills"].empty()){
        jsn["skills"].erase(jsn["skills"].begin());
    }
    else{
        cout<<"Person has not mention any skills"<<endl;}

    cout<<"\n--Display Updated data:"<<endl;
    cout<<"Name: "<<jsn["name"]<<endl;
    cout<<"Mobile Number: "<<jsn["mobile_no"]<<endl;
    cout<<"University or College Name: "<<jsn["university"]<<endl;
    if(jsn["is_fresher"]){
        cout<<"Is Fresher: Yes"<<endl;
    }else{
        cout<<"Is Fresher: No"<<endl;
    }
    cout<<"Skills: ";
    for(int i = 0; i < jsn["skills"].size(); i++) {
        cout << jsn["skills"][i] << " ";
    }

    ofstream outputFile("updatedjsondata.json");    
    outputFile << jsn.dump(4);
    cout<<"\nAll changes saved to 'updatedjsondata.json' file"<<endl;
    outputFile.close();
    return 0;
}

 

In the given example code, the nlohmann/json library is utilized to parse JSON data by first opening the jsonfile.json with ifstream. If the file opens without issues, its content is read into a json object called jsn using the >> operator. The attributes such as “name”, “mobile_no”, “university”, and “is_fresher” are accessed as key-value pairs and printed to the console. The program then updates some fields, adds a new skill with push_back(), and deletes the first skill using erase(). Ultimately, the modified JSON data is written to a new file, “updatedjsondata.json”, with ofstream and formatted using dump(4) for improved readability with indentation. This illustrates how JSON parsing, modification, and serialization can be effectively managed in C++ with the nlohmann/json library.

Output

-|- Parsing done -|-
--Display Old data:
Name: Arshi
Mobile Number: 123456789
University or College Name: SPPU
Is Fresher: Yes
Skills: "C++" "Python" "AI" "Cloud Computing" 
--Display Updated data:
Name: "Asmita"
Mobile Number: 9876543210
University or College Name: "RSU"
Is Fresher: No
Skills: "Python" "AI" "Cloud Computing" "ML" 
All changes saved to the 'updatedjsondata.json' file!!!!

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top