value__object_t_key_type.cpp 815 B

123456789101112131415161718192021222324252627282930
  1. #include <iostream>
  2. #include <nlohmann/json.hpp>
  3. using json = nlohmann::json;
  4. int main()
  5. {
  6. // create a JSON object with different entry types
  7. json j =
  8. {
  9. {"integer", 1},
  10. {"floating", 42.23},
  11. {"string", "hello world"},
  12. {"boolean", true},
  13. {"object", {{"key1", 1}, {"key2", 2}}},
  14. {"array", {1, 2, 3}}
  15. };
  16. // access existing values
  17. int v_integer = j.value("integer", 0);
  18. double v_floating = j.value("floating", 47.11);
  19. // access nonexisting values and rely on default value
  20. std::string v_string = j.value("nonexisting", "oops");
  21. bool v_boolean = j.value("nonexisting", false);
  22. // output values
  23. std::cout << std::boolalpha << v_integer << " " << v_floating
  24. << " " << v_string << " " << v_boolean << "\n";
  25. }