From a41b7899955a2bf54315fc2507f8e2f010ff271a Mon Sep 17 00:00:00 2001 From: m-holger Date: Sun, 14 Jan 2024 16:38:51 +0000 Subject: [PATCH] Add new method JSON::getDictItem --- include/qpdf/JSON.hh | 2 ++ libqpdf/JSON.cc | 11 +++++++++++ libtests/json.cc | 6 ++++++ 3 files changed, 19 insertions(+) diff --git a/include/qpdf/JSON.hh b/include/qpdf/JSON.hh index 81abe89c..e3c8a7dc 100644 --- a/include/qpdf/JSON.hh +++ b/include/qpdf/JSON.hh @@ -162,6 +162,8 @@ class JSON QPDF_DLL bool isNull() const; QPDF_DLL + JSON getDictItem(std::string const& key) const; + QPDF_DLL bool forEachDictItem(std::function fn) const; QPDF_DLL bool forEachArrayItem(std::function fn) const; diff --git a/libqpdf/JSON.cc b/libqpdf/JSON.cc index f6401642..35b8fd76 100644 --- a/libqpdf/JSON.cc +++ b/libqpdf/JSON.cc @@ -410,6 +410,17 @@ JSON::isNull() const return m->value->type_code == vt_null; } +JSON +JSON::getDictItem(std::string const& key) const +{ + if (auto v = dynamic_cast(m->value.get())) { + if (auto it = v->members.find(key); it != v->members.end()) { + return it->second; + } + } + return makeNull(); +} + bool JSON::forEachDictItem(std::function fn) const { diff --git a/libtests/json.cc b/libtests/json.cc index 98e332e7..f265f6f6 100644 --- a/libtests/json.cc +++ b/libtests/json.cc @@ -78,6 +78,12 @@ test_main() jmap.addDictionaryMember("empty_dict", JSON::makeDictionary()); jmap.addDictionaryMember("empty_list", JSON::makeArray()); jmap.addDictionaryMember("single", JSON::makeArray()).addArrayElement(JSON::makeInt(12)); + std::string jm_str; + assert(jmap.getDictItem("b").getString(jm_str)); + assert(!jmap.getDictItem("b2").getString(jm_str)); + assert(!jstr2.getDictItem("b").getString(jm_str)); + assert(jm_str == "a\tb"); + check( jmap, "{\n"