C++ program to convert JSON elements into an array
In this tutorial, we’ll learn how to convert JSON elements into an array using C++ programming language. C++ directly cannot read the JSON values. So, we need to build an associate array.
For converting JSON elements into an array we need to include Json nlohmann library inside our code.
Now let us see the basic syntax for Json nlohmann library.
static basic_json nlohmann::basic_json::array(initializer_list_t init = {})
The above is the basic syntax for json nlohmann. As told above we have taken an associate array as C++ cannot directly read the JSON values.
How to convert JSON elements into an array
For a better understanding of the below program kindly follow the below link
Generate random JSON data using C++
Now let us see a program on how to convert JSON elements into an array
Program:
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { json no_init_list = json::array(); json empty_init_list = json::array({}); json nonempty_init_list = json::array({1, 2, 3, 4, 5, 6, 7, 8}); json list_of_pairs = json::array({ {"one", 1}, {"two", 2}, {"three", 3}, {"four", 4}, {"five", 5} }); std::cout << no_init_list << '\n'; std::cout << empty_init_list << '\n'; std::cout << nonempty_init_list << '\n'; std::cout << list_of_pairs << '\n'; }
Output:
[] [] [1,2,3,4,5,6,7,8] [["one",1],["two",2],["three",3],["four",4],["five",5]]
That’s it…
We have successfully been able to convert JSON formatted data into an array with the help of C++ language.
Leave a Reply