C++ Json::array()

C++ Json::array()


In the Json Introduction article, you have come to know how to include Json nlohmann library into your code. Here we will go through one of the functions in Json Library.(i.e.array()).
  •  This function creates a JSON array value from the given initializer list. (i.e., If the values given in the initializer list are 1,2,3 it creates the JSON  value [1,2,3]. This can be further used in your code.
  • This function is the constructor of basic_json. ( basic_json is the class template for JSON values).           

        static basic_json nlohmann::basic_json::array(initializer_list_t init = {})


This function is mainly needed to express two cases which cannot be realized with initializer list constructor (basic_json(initializer_list_t,bool,value_t).
  • If the given initializer list is empty, then the empty array [ ] is created.
  •  If the initializer list contains all the pairs whose first element is a string, then in this case the initializer list constructor would create an object, taking the first elements as keys.

Return Value:

        It returns JSON Array Value.


#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;
using namespace std;

int main()
// creating JSON arrays
json no_list = json::
json nonempty_int_list = json::
array({2, 4, 6, 8, 10, 12});
json nonempty_float_list = json::
json list_of_pairs = json::
array({ {"one", 1}, {"two", 2} ,{"three", 3}});
json empty_list = json::

// serialize the JSON arrays
std::cout << no_list << endl;
std::cout << nonempty_int_list << endl;
std::cout << nonempty_float_list << endl;
std::cout << list_of_pairs << endl;
std::cout << empty_list << endl;


[2,4,6,8,10,12] [1.2,5.5,6.7] [["one",1],["two",2],["three",3]] []