Skip to content
Related Articles

Related Articles

Improve Article

How to communicate JSON data between C++ and Node.js ?

  • Difficulty Level : Basic
  • 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"
  
// For convenience
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
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :