• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <iostream>
2 #include <nlohmann/json.hpp>
3 
4 using json = nlohmann::json;
5 
main()6 int main()
7 {
8     // create JSON values
9     json j_object = {{"one", 1}, {"two", 2}};
10     json j_array = {1, 2, 4, 8, 16};
11     json j_string = "Hellö ��!";
12 
13     // call dump()
14     std::cout << "objects:" << '\n'
15               << j_object.dump() << "\n\n"
16               << j_object.dump(-1) << "\n\n"
17               << j_object.dump(0) << "\n\n"
18               << j_object.dump(4) << "\n\n"
19               << j_object.dump(1, '\t') << "\n\n";
20 
21     std::cout << "arrays:" << '\n'
22               << j_array.dump() << "\n\n"
23               << j_array.dump(-1) << "\n\n"
24               << j_array.dump(0) << "\n\n"
25               << j_array.dump(4) << "\n\n"
26               << j_array.dump(1, '\t') << "\n\n";
27 
28     std::cout << "strings:" << '\n'
29               << j_string.dump() << '\n'
30               << j_string.dump(-1, ' ', true) << '\n';
31 
32     // create JSON value with invalid UTF-8 byte sequence
33     json j_invalid = "ä\xA9ü";
34     try
35     {
36         std::cout << j_invalid.dump() << std::endl;
37     }
38     catch (json::type_error& e)
39     {
40         std::cout << e.what() << std::endl;
41     }
42 
43     std::cout << "string with replaced invalid characters: "
44               << j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)
45               << "\nstring with ignored invalid characters: "
46               << j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)
47               << '\n';
48 }
49