Look up the key only once in the callback parser's key() (#5831)

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
This commit is contained in:
Niels Lohmann authored and GitHub committed 2026-10-15 20:01:19 +02:00
1 parent 4e294f4b18
commit a6e9785ab6
2 files changed
+12 -6

No files matched your search

+6 -3
View File
@@ -674,16 +674,19 @@ class json_sax_dom_callback_parser
if (keep && ref_stack.back()) if (keep && ref_stack.back())
{ {
auto& obj = *ref_stack.back()->m_data.m_value.object; auto& obj = *ref_stack.back()->m_data.m_value.object;
const auto it = obj.find(val); // a single lookup: insert the placeholder, or find the existing member
if (it != obj.end()) const auto inserted = obj.emplace(val, discarded);
const auto it = inserted.first;
if (!inserted.second)
{ {
// this is a duplicate key (legal in JSON); remember its // this is a duplicate key (legal in JSON); remember its
// current value so it can be restored later if the new // current value so it can be restored later if the new
// value is rejected by the callback, instead of being // value is rejected by the callback, instead of being
// erased together with the discarded placeholder // erased together with the discarded placeholder
duplicate_key_stash.emplace_back(&(it->second), it->second); duplicate_key_stash.emplace_back(&(it->second), it->second);
it->second = discarded;
} }
object_element = &(obj[val] = discarded); object_element = &(it->second);
} }
return true; return true;
+6 -3
View File
@@ -13850,16 +13850,19 @@ class json_sax_dom_callback_parser
if (keep && ref_stack.back()) if (keep && ref_stack.back())
{ {
auto& obj = *ref_stack.back()->m_data.m_value.object; auto& obj = *ref_stack.back()->m_data.m_value.object;
const auto it = obj.find(val); // a single lookup: insert the placeholder, or find the existing member
if (it != obj.end()) const auto inserted = obj.emplace(val, discarded);
const auto it = inserted.first;
if (!inserted.second)
{ {
// this is a duplicate key (legal in JSON); remember its // this is a duplicate key (legal in JSON); remember its
// current value so it can be restored later if the new // current value so it can be restored later if the new
// value is rejected by the callback, instead of being // value is rejected by the callback, instead of being
// erased together with the discarded placeholder // erased together with the discarded placeholder
duplicate_key_stash.emplace_back(&(it->second), it->second); duplicate_key_stash.emplace_back(&(it->second), it->second);
it->second = discarded;
} }
object_element = &(obj[val] = discarded); object_element = &(it->second);
} }
return true; return true;