parse__allow_exceptions.cpp 662 B

123456789101112131415161718192021222324252627282930313233343536
  1. #include <iostream>
  2. #include <nlohmann/json.hpp>
  3. using json = nlohmann::json;
  4. int main()
  5. {
  6. // an invalid JSON text
  7. std::string text = R"(
  8. {
  9. "key": "value without closing quotes
  10. }
  11. )";
  12. // parse with exceptions
  13. try
  14. {
  15. json j = json::parse(text);
  16. }
  17. catch (json::parse_error& e)
  18. {
  19. std::cout << e.what() << std::endl;
  20. }
  21. // parse without exceptions
  22. json j = json::parse(text, nullptr, false);
  23. if (j.is_discarded())
  24. {
  25. std::cout << "the input is invalid JSON" << std::endl;
  26. }
  27. else
  28. {
  29. std::cout << "the input is valid JSON: " << j << std::endl;
  30. }
  31. }