How to communicate JSON data between C++ and Node.js ?
Last Updated :
31 May, 2021
In this article, we will use JSON data to communicate between two programs called C++ and Node.js. We can use a common text format to communicate, but text format will contain a lot of complexities. However, JSON is lightweight and easy to use. JSON is language-independent and hence can be used by any programming language.
Serialization using C++: Serialization is the process of converting programming data to JSON text. In C++, there is no inbuilt library for JSON readers. We need to add the header file to our project. You will basically need json.hpp file for your C++ project to do the below-described stuff.
Let us generate a JSON file using C++ code as follows.
C++
#include<iostream>
#include<ofstream>
#include "json.hpp"
using json = nlohmann::json;
using namespace std;
int main(){
json obj;
obj[ "Name" ] = "Inshal" ;
obj[ "Roll no" ] = "42" ;
obj[ "Dept" ] = "CSE" ;
obj[ "cgpa" ] = "7.99" ;
ofstream file( "output.json" );
file<<setw(4)<<obj<<endl;
file.close();
cout<< "JSON Object Created:" ;
for ( auto & element : obj) {
cout << element << '\n' ;
}
}
|
Output:
JSON Object Created:{
"Name":"Inshal",
"Roll no":"42",
"Dept":"CSE",
"cgpa":"7.99"
}
Deserialization using Node.js:
Javascript
'use strict' ;
const fs = require( 'fs' );
fs.readFile( 'output.json' , (err, data) => {
if (err) throw err;
let obj = JSON.parse(data);
console.log(obj);
});
console.log( 'File Reading completed' );
|
Output:
JSON file created:{
"name":"Inshal Khan",
"Roll no":"42",
"cgpa":"7.99"}
File Reading completed
Share your thoughts in the comments
Please Login to comment...