Hello everyone, today I’m going to talk about an awesome c++ library which I had used often to save data in files much more effectively and efficiency.

You can find the JSON library in this github repo. You will basically need json.hpp file for your C++ project to do the bellow described stuff.

Before I start talking about this, I should mention this. I have directly copy the codes/ figures from original JSON library github repo. I thought it is easy to explain with those examples explain on there wiki. And also, for more details you can refer that too.

01 – What are the things can be done with json library?
Well, you can basically create json object in your C++ project with this library. And the awesome thing is, you can convert that json object into json file and save them. Also you can read json files and create json objects again. Trust me, it is much fast and easy to use!

02 – Getting started
First you need to get the json.hpp file from the github repo. make sure to get a released version. Before starting coding you need to include the json file and then you need to extend the namespace. For the  you can add following lines for your code.

#include "json.hpp"

// for convenience
using json = nlohmann::json;

If you do not like to add the above line as using json = nlohmann::json; , then you have to type your code nlohmann::json;  in every line you type.

03 – make a simple json class
You can make a simple json as follow

// create an empty structure (null)
json j;

// add a number that is stored as double (note the implicit conversion of j to an object)
j["pi"] = 3.141;

// add a Boolean that is stored as bool
j["happy"] = true;

// add a string that is stored as std::string
j["name"] = "Niels";

// add another null object by passing nullptr
j["nothing"] = nullptr;

// add an object inside the object
j["answer"]["everything"] = 42;

// add an array that is stored as std::vector (using an initializer list)
j["list"] = { 1, 0, 2 };

// add another object (using an initializer list of pairs)
j["object"] = { {"currency", "USD"}, {"value", 42.99} };

// instead, you could also write (which looks very similar to the JSON above)
json j2 = {
  {"pi", 3.141},
  {"happy", true},
  {"name", "Niels"},
  {"nothing", nullptr},
  {"answer", {
    {"everything", 42}
  }},
  {"list", {1, 0, 2}},
  {"object", {
    {"currency", "USD"},
    {"value", 42.99}
  }}
};

04 – read write json file

you can write your json objects in to a json file directly as follow.

// write prettified JSON to another file
std::ofstream o("pretty.json");
o << std::setw(4) << j << std::endl;

you can read a json file into a json object directly as follow

// read a JSON file
std::ifstream i("file.json");
json j;
i >> j;

05 – access data of json
since you can save, read data from json files, it is very easy to handle data. You can easily access different type of data in between different languages with this method.
lets see how to convert C++ data (vector) into json & json object into C++ vector. So you will be easily access data in between those two fields.

following codes will show you how to do above things.

// create an array using push_back
json j;
j.push_back("foo");
j.push_back(1);
j.push_back(true);

// also use emplace_back
j.emplace_back(1.78);

// iterate the array
for (json::iterator it = j.begin(); it != j.end(); ++it) {
  std::cout << *it << 'n';
}

// range-based for
for (auto& element : j) {
  std::cout << element << 'n';
}

// getter/setter
const std::string tmp = j[0];
j[1] = 42;
bool foo = j.at(2);

// comparison
j == "["foo", 1, true]"_json;  // true

// other stuff
j.size();     // 3 entries
j.empty();    // false
j.type();     // json::value_t::array
j.clear();    // the array is empty again

// convenience type checkers
j.is_null();
j.is_boolean();
j.is_number();
j.is_object();
j.is_array();
j.is_string();

// create an object
json o;
o["foo"] = 23;
o["bar"] = false;
o["baz"] = 3.141;

// also use emplace
o.emplace("weather", "sunny");

// special iterator member functions for objects
for (json::iterator it = o.begin(); it != o.end(); ++it) {
  std::cout << it.key() << " : " << it.value() << "n";
}

// find an entry
if (o.find("foo") != o.end()) {
  // there is an entry with key "foo"
}

// or simpler using count()
int foo_present = o.count("foo"); // 1
int fob_present = o.count("fob"); // 0

// delete an entry
o.erase("foo");
std::vector<int> c_vector {1, 2, 3, 4};
json j_vec(c_vector);
// [1, 2, 3, 4]

std::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};
json j_deque(c_deque);
// [1.2, 2.3, 3.4, 5.6]

std::list<bool> c_list {true, true, false, true};
json j_list(c_list);
// [true, true, false, true]

std::forward_list<int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};
json j_flist(c_flist);
// [12345678909876, 23456789098765, 34567890987654, 45678909876543]

std::array<unsigned long, 4> c_array {{1, 2, 3, 4}};
json j_array(c_array);
// [1, 2, 3, 4]

std::set<std::string> c_set {"one", "two", "three", "four", "one"};
json j_set(c_set); // only one entry for "one" is used
// ["four", "one", "three", "two"]

std::unordered_set<std::string> c_uset {"one", "two", "three", "four", "one"};
json j_uset(c_uset); // only one entry for "one" is used
// maybe ["two", "three", "four", "one"]

std::multiset<std::string> c_mset {"one", "two", "one", "four"};
json j_mset(c_mset); // both entries for "one" are used
// maybe ["one", "two", "one", "four"]

std::unordered_multiset<std::string> c_umset {"one", "two", "one", "four"};
json j_umset(c_umset); // both entries for "one" are used
// maybe ["one", "two", "one", "four"]
// {"one": 1, "three": 3, "two": 2 }
To catch this kind of small tutorials, and things I do for fun, don’t forget to subscribe my BloggerYouTube & follow me on GitHub.
Do you facing any issues while trying this? Let’s discuss in bellow…

 

***Please note that all of the content on this post was originally published on champlnx.blogspot.com. We have migrated these posts to www.champlnx.com for your convenience and continued access.

One Response

Leave a Reply

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