parse__istream__parser_callback_t.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <sstream>
  4. #include <nlohmann/json.hpp>
  5. using json = nlohmann::json;
  6. int main()
  7. {
  8. // a JSON text
  9. auto text = R"(
  10. {
  11. "Image": {
  12. "Width": 800,
  13. "Height": 600,
  14. "Title": "View from 15th Floor",
  15. "Thumbnail": {
  16. "Url": "http://www.example.com/image/481989943",
  17. "Height": 125,
  18. "Width": 100
  19. },
  20. "Animated" : false,
  21. "IDs": [116, 943, 234, 38793]
  22. }
  23. }
  24. )";
  25. // fill a stream with JSON text
  26. std::stringstream ss;
  27. ss << text;
  28. // parse and serialize JSON
  29. json j_complete = json::parse(ss);
  30. std::cout << std::setw(4) << j_complete << "\n\n";
  31. // define parser callback
  32. json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)
  33. {
  34. // skip object elements with key "Thumbnail"
  35. if (event == json::parse_event_t::key and parsed == json("Thumbnail"))
  36. {
  37. return false;
  38. }
  39. else
  40. {
  41. return true;
  42. }
  43. };
  44. // fill a stream with JSON text
  45. ss.clear();
  46. ss << text;
  47. // parse (with callback) and serialize JSON
  48. json j_filtered = json::parse(ss, cb);
  49. std::cout << std::setw(4) << j_filtered << '\n';
  50. }