C++ Json::array()














































C++ Json::array()



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).           
Syntax:

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

Importance:

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.

Example:

#include <iostream>
#include<bits/stdc++.h>
#include <nlohmann/json.hpp>

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

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

// 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;
}

Output:

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



Comments