parse__string__parser_callback_t.cpp 1.2 KB

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