C++ Json::dump()














































C++ Json::dump()



Json::dump()

In this article we will go through one of the Object Inspection Functions of Json Nlohmann library named dump(). It is the Serialization function of Json Values and it currently supports its indent.

Syntax:

string_t nlohmann::basic_json::dump ( const int indent = -1, const char indent_char = ' ', const bool ensure_ascii = false, const error_handler_t error_handler=error_handler_t::strict ) const
indent : The array elements and objects will be printed based on the indent specified here if the
indent provided is non negative. The default value is -1.
indent_char : It specifies the character to use for the indentation if the indent provided is greater
than 0.
ensure_ascii : If this parameter is given as true, then all the non-ASCII characters in the output will
be escaped with \uXXXX sequences and the final result consists of ASCII
characters only.

Return Value:

It returns the string containing the serialization of Json value.

Example:

#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; using namespace std; int main() { // create JSON values json j_array = {100, 200, 300, 400, 500}; json j_object = {{"Animal", "Dog"}, {"Bird", "Peacock"}, {"Fruit", "Mango"} }; json j_string = "Hello!!!"; // calling dump() on array. std::cout << "arrays formed after executing dump:" << "\n\n" << j_array.dump() << "\n\n" << j_array.dump(-1) << "\n\n" << j_array.dump(0) << "\n\n" << j_array.dump(4) << "\n\n" << j_array.dump(1, '\t') << "\n\n"; std::cout<<"-------------------------------------------"<<'\n'; // calling dump() on object. std::cout << "objects formed after executing dump:" << "\n\n" << j_object.dump() << "\n\n" << j_object.dump(-1) << "\n\n" << j_object.dump(1, '\t') << "\n\n" << j_object.dump(0) << "\n\n" << j_object.dump(4) << "\n\n"; std::cout<<"-------------------------------------------"<<'\n'; // calling dump() on string. std::cout << "string formed after executing dump:" << "\n\n" << j_string.dump(4) << '\n'; }
Output:
Arrays formed after executing dump: [100,200,300,400,500] [100,200,300,400,500] [ 100, 200, 300, 400, 500 ] [ 100, 200, 300, 400, 500 ] [ 100, 200, 300, 400, 500 ] ------------------------------------------- objects formed after executing dump: {"Animal":"Dog","Bird":"Peacock","Fruit":"Mango"} {"Animal":"Dog","Bird":"Peacock","Fruit":"Mango"} { "Animal": "Dog", "Bird": "Peacock", "Fruit": "Mango" } { "Animal": "Dog", "Bird": "Peacock", "Fruit": "Mango" } { "Animal": "Dog", "Bird": "Peacock", "Fruit": "Mango" } ------------------------------------------- string formed after executing dump: "Hello!!!"

Exceptions

type_error.316 : If the string stored in the Json Value is not UTF-8 encoded, then 
                          this exception occurs.



Comments