C++ Json

Spread the love

C++ Json libraries

There are at least 3 major, well used c++ json libraries used for reading and writing to json data structures. Our plan is not to use any of them. We are going to first focus on what a json structure looks like, then look at how we might traverse such a structure in much the same way that a javascript coder might do so.

But for those who are looking for a c++ json reader that can traverse the nodes there is a good free example or two up on Github.

This is a very useful definition of Json.

JSON comes from JavaScript object notation syntax:

  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays

So, let’s create a Json object as a string.

##include <iostream>

using namespace std;

int main() {
   string strJson1, strJson2, strJson3, strJson4;
   strJson1 = "{}"; // Curly braces
   strJson2 = "{name\":\"John Smith\"}"; //1 data item
   strJson3 = "{\"name\":\"John\",\"name\":\"Janet\"}"; //2 data items
   strJson4 = "{\"employees\":[{\"firstName\":\"John\",\"lastName\":\"Doe\"}]}"; 
   cout << strJson1 << endl;
   cout << strJson2 << endl;
   cout << strJson3 << endl;
   cout << strJson4 << endl;

   return 0;

c++Json file formats

Output from the json experimental code above. You may have noticed the unsightly \ \ \ all over the code above. Those are our attempts to escape the double quotes that are required for c++ Json keys.

What we are looking at below are 4 different forms of Json files.

Will continue this c++ json in another lesson.

Homework: Look at the different formats that a json file can take. There is actually only one format but there are about 7 different object types that can be in a json object. Research to find out what they are and write some sample c++ json files with arrays, name:value pairs, other objects, booleans, dates