Commit a41b7899955a2bf54315fc2507f8e2f010ff271a

Authored by m-holger
1 parent 7315aa8c

Add new method JSON::getDictItem

include/qpdf/JSON.hh
@@ -162,6 +162,8 @@ class JSON @@ -162,6 +162,8 @@ class JSON
162 QPDF_DLL 162 QPDF_DLL
163 bool isNull() const; 163 bool isNull() const;
164 QPDF_DLL 164 QPDF_DLL
  165 + JSON getDictItem(std::string const& key) const;
  166 + QPDF_DLL
165 bool forEachDictItem(std::function<void(std::string const& key, JSON value)> fn) const; 167 bool forEachDictItem(std::function<void(std::string const& key, JSON value)> fn) const;
166 QPDF_DLL 168 QPDF_DLL
167 bool forEachArrayItem(std::function<void(JSON value)> fn) const; 169 bool forEachArrayItem(std::function<void(JSON value)> fn) const;
libqpdf/JSON.cc
@@ -410,6 +410,17 @@ JSON::isNull() const @@ -410,6 +410,17 @@ JSON::isNull() const
410 return m->value->type_code == vt_null; 410 return m->value->type_code == vt_null;
411 } 411 }
412 412
  413 +JSON
  414 +JSON::getDictItem(std::string const& key) const
  415 +{
  416 + if (auto v = dynamic_cast<JSON_dictionary const*>(m->value.get())) {
  417 + if (auto it = v->members.find(key); it != v->members.end()) {
  418 + return it->second;
  419 + }
  420 + }
  421 + return makeNull();
  422 +}
  423 +
413 bool 424 bool
414 JSON::forEachDictItem(std::function<void(std::string const& key, JSON value)> fn) const 425 JSON::forEachDictItem(std::function<void(std::string const& key, JSON value)> fn) const
415 { 426 {
libtests/json.cc
@@ -78,6 +78,12 @@ test_main() @@ -78,6 +78,12 @@ test_main()
78 jmap.addDictionaryMember("empty_dict", JSON::makeDictionary()); 78 jmap.addDictionaryMember("empty_dict", JSON::makeDictionary());
79 jmap.addDictionaryMember("empty_list", JSON::makeArray()); 79 jmap.addDictionaryMember("empty_list", JSON::makeArray());
80 jmap.addDictionaryMember("single", JSON::makeArray()).addArrayElement(JSON::makeInt(12)); 80 jmap.addDictionaryMember("single", JSON::makeArray()).addArrayElement(JSON::makeInt(12));
  81 + std::string jm_str;
  82 + assert(jmap.getDictItem("b").getString(jm_str));
  83 + assert(!jmap.getDictItem("b2").getString(jm_str));
  84 + assert(!jstr2.getDictItem("b").getString(jm_str));
  85 + assert(jm_str == "a\tb");
  86 +
81 check( 87 check(
82 jmap, 88 jmap,
83 "{\n" 89 "{\n"