dump.cpp 1.4 KB

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