mirror of
https://github.com/nlohmann/json.git
synced 2026-08-11 19:53:18 +00:00
Follow-up to #5342, which fixed the parser callback leaving a discarded member behind when an array or a value under an object key was rejected. The documentation of parser_callback_t only stated that discarded values in structured types are skipped, without saying that this covers object parents and that the key is removed along with the value, so there was no way to tell the fixed behavior from the buggy one. Spell out the discarding rules, add an example that exercises the cases the fix repaired, and correct the return value description: a discarded top-level value is replaced by null, not by "an empty discarded object". Signed-off-by: Niels Lohmann <mail@nlohmann.me>
48 lines
1.6 KiB
C++
48 lines
1.6 KiB
C++
#include <iostream>
|
|
#include <nlohmann/json.hpp>
|
|
|
|
using json = nlohmann::json;
|
|
|
|
int main()
|
|
{
|
|
// a JSON text with an array and a number inside an object
|
|
auto text = R"({"IDs": [116, 943], "Width": 800})";
|
|
|
|
// discard the array when the parser reads its opening bracket
|
|
json j_array_start = json::parse(text, [](int /*depth*/, json::parse_event_t event, json & /*parsed*/)
|
|
{
|
|
return event != json::parse_event_t::array_start;
|
|
});
|
|
|
|
// discard the same array when the parser reads its closing bracket
|
|
json j_array_end = json::parse(text, [](int /*depth*/, json::parse_event_t event, json & /*parsed*/)
|
|
{
|
|
return event != json::parse_event_t::array_end;
|
|
});
|
|
|
|
// discard the number, but keep its key
|
|
json j_value = json::parse(text, [](int /*depth*/, json::parse_event_t event, json & parsed)
|
|
{
|
|
return !(event == json::parse_event_t::value && parsed == json(800));
|
|
});
|
|
|
|
// discard the key of the number
|
|
json j_key = json::parse(text, [](int /*depth*/, json::parse_event_t event, json & parsed)
|
|
{
|
|
return !(event == json::parse_event_t::key && parsed == json("Width"));
|
|
});
|
|
|
|
// discard the top-level object
|
|
json j_root = json::parse(text, [](int /*depth*/, json::parse_event_t event, json & /*parsed*/)
|
|
{
|
|
return event != json::parse_event_t::object_end;
|
|
});
|
|
|
|
// in every case, the discarded value is removed together with its key
|
|
std::cout << j_array_start << '\n'
|
|
<< j_array_end << '\n'
|
|
<< j_value << '\n'
|
|
<< j_key << '\n'
|
|
<< j_root << '\n';
|
|
}
|