Write and Parse JSON in CPP

CPPParse JSON in CPPWrite JSON in CPP

CPP does not support native JSON parsers and creators. There are many JSON libraries available in CPP. The most loved by the developer JSON library for CPP is nlohmann/JSON, which was written in C++11. Let's discuss how to write and read JSON in CPP.

Consider the following sample JSON Document :

{
    "name" : "File.mp3",
    "size" : "25Mb",
    "section" : [ 1 , 2, 3 , 4 ],
    "updateby" : [
     {
         "name" : "user one",
         "date" : "10:00 21 May",
         "userrole" : [ "add", "update", "delete"]
     },
     {
         "name" : "user two",
         "date" : "10:00 21 May",
         "userrole" : [ "add", "delete"]
     }],
    "Metadata" : { "create" : "21 MAy", "audio" : "acc", "video" : "H264"}
}

In the above sample JSON, we covered JSON objects, JSON Array, and nested JSON forms.

Setup

Click here to get the latest nlohmann/JSON. Download the zip file, Once this is done, we need an json.hpp header file which consists of the whole code. This is the main advantage of this JSON parser, no need for .so, .a, or nither required any complicated pre-builds.

#include "<filepath>/json.hpp"


Write JSON in C++

STEP 1: To write JSON, First you need to include a json.hpp file and create a JSON Object.

#include "<filepath>/json.hpp"
json jsonData;

STEP 2: For Key value pairs, we can assign values to the respective key in the created object.

jsonData["name"] = "File.mp3";
jsonData["size"] = "25Mb";

STEP 3: To create JSON Array, assign an array of any data type to the respective key.

int intarray[] = {1, 2, 3, 4};
jsonData["list"] = intarray;

STEP 4: Similarly, we can assign any JSON object to the respective key.

json metaDataJsonObj;
metaDataJsonObj["create"] = "21 MAy";
metaDataJsonObj["audio"] = "acc";
metaDataJsonObj["video"] = "H264";

//Adding JSON object to the JSON object as a value
jsonData["Metadata"] = metaDataJsonObj;

STEP 5: With the help of the dump() function, we can convert JSON to String.

jsonData.dump()

Let’s see a complete code of write JSON data in CPP :

#include "iostream"
#include "iomanip"
#include "simpleCppJsonWriter.hpp"
#include "json.hpp"

using json = nlohmann::json;

simpleCppJsonWriter::simpleCppJsonWriter() {
}

simpleCppJsonWriter::~simpleCppJsonWriter() {
}

std::string simpleCppJsonWriter::WriteJson() {
	// creating JSON Object
	json jsonData;

	// creating key value pair JSON Object
	jsonData["name"] = "File.mp3";
	jsonData["size"] = "25Mb";
	jsonData["section"] = "25Mb";

	//Creating a JSON Array
	int intarray[] = {1, 2, 3, 4};
	jsonData["list"] = intarray;

	// creating JSON Object
	json updateListJsonObj_one;
	updateListJsonObj_one["name"] = "user one";
	updateListJsonObj_one["date"] = "10:00 21 May";
	updateListJsonObj_one["userrole"] = { "add", "update", "delete"};

	// creating JSON Object
	json updateListJsonObj_two;
	updateListJsonObj_two["name"] = "user two";
	updateListJsonObj_two["date"] = "10:00 21 May";
	updateListJsonObj_two["userrole"] = { "add", "delete"};

	//Adding array to the JSON object as a value
	jsonData["updateby"] = { updateListJsonObj_one, updateListJsonObj_two };

	// creating JSON Object
	json metaDataJsonObj;
	metaDataJsonObj["create"] = "21 MAy";
	metaDataJsonObj["audio"] = "acc";
	metaDataJsonObj["video"] = "H264";

	//Adding JSON object to the JSON object as a value
	jsonData["Metadata"] = metaDataJsonObj;

	std::cout << "	Output JSON : "<< jsonData.dump() << std::endl;
	return jsonData.dump();
}


Parse JSON in C++

STEP 1: To parse JSON, First, you need to include a json.hpp file and with the help of json::parse() function, we can create a JSON Object.

std::string _jsondata = "{"name":"File.mp3","size":"25Mb","section":[1,2,3,4],"updateby":[{"name":"user one","date":"10:00 21 May","userrole":["add","update","delete"]},{"name":"user two","date":"10:00 21 May","userrole":["add","delete"]}],"Metadata":{"create":"21 MAy","audio":"acc","video":"H264"}}";

// parse string in JSON Object
json jsonData = json::parse(_jsondata);

STEP 2: Initialize any control flow statement to extract data from Object.

for (auto it = jsonData.begin(); it != jsonData.end(); ++it) {

STEP 3: To identify primitive data types, nlohmann/JSON support is_null(), is_string(), is_boolean(), is_number(), and is_binary() methods and similarly we can identify array and object.

//To Identify String
it.value().is_number()

//To Identify Object
it.value().is_object()

Let’s see a complete code of parse JSON data in CPP:

#include "iostream"
#include "simpleCppJsonParser.hpp"
#include "json.hpp"

using json = nlohmann::json;

simpleCppJsonParser::simpleCppJsonParser() {
}

simpleCppJsonParser::~simpleCppJsonParser() {
}

void simpleCppJsonParser::ParserJson(std::string _jsondata) {
	// parse string in JSON Object
	json jsonData = json::parse(_jsondata);

	for (auto it = jsonData.begin(); it != jsonData.end(); ++it) {

		//Gets all key from JSON object
		std::cout << "	*)  key: " << it.key() << " | value:" << it.value();

	    // convenience type checkers
	    if(it.value().is_null()) {
	    	std::cout << "Value is null" << std::endl;
	    } else if(it.value().is_boolean()) {
	    	std::cout << "Value is boolean:" << it.value() << std::endl;
	    } else if(it.value().is_number()) {
	    	std::cout << "Value is number :" << it.value() << std::endl;
	    } else if(it.value().is_object()) {
	    	std::cout << "Value is object :" << it.value() << std::endl;

	    	//Parse Array
	    	for (auto& jsonObject : it.value().items())
	    	{
	    		std::cout << "Object key : " << jsonObject.key() << " | value: " << jsonObject.value();
	    	}
	    } else if(it.value().is_array()) {
	    	std::cout << "Value is array  :" << it.value() << std::endl;

	    	//Parse Array
	    	for (auto& array : it.value().items())
	    	{
	    		std::cout << "Array position : " << array.key() << " | value: " << array.value();
	    	}

	    } else if(it.value().is_string()) {
	    	std::cout << "Value is string :" << it.value() << std::endl;
	    } else {
	    	std::cout << "Unknown data type!!" << std::endl;
	    }
	    std::cout << std::endl;
	}
	return ;
}

Download


nlohmann/json : Click here

Source Code : Click here

Credits


nlohmann/json - CPP JSON encoders/decoders library

json.org - Introducing JSON Standard