Commit a41b7899955a2bf54315fc2507f8e2f010ff271a
1 parent
7315aa8c
Add new method JSON::getDictItem
Showing
3 changed files
with
19 additions
and
0 deletions
include/qpdf/JSON.hh
| ... | ... | @@ -162,6 +162,8 @@ class JSON |
| 162 | 162 | QPDF_DLL |
| 163 | 163 | bool isNull() const; |
| 164 | 164 | QPDF_DLL |
| 165 | + JSON getDictItem(std::string const& key) const; | |
| 166 | + QPDF_DLL | |
| 165 | 167 | bool forEachDictItem(std::function<void(std::string const& key, JSON value)> fn) const; |
| 166 | 168 | QPDF_DLL |
| 167 | 169 | bool forEachArrayItem(std::function<void(JSON value)> fn) const; | ... | ... |
libqpdf/JSON.cc
| ... | ... | @@ -410,6 +410,17 @@ JSON::isNull() const |
| 410 | 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 | 424 | bool |
| 414 | 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 | 78 | jmap.addDictionaryMember("empty_dict", JSON::makeDictionary()); |
| 79 | 79 | jmap.addDictionaryMember("empty_list", JSON::makeArray()); |
| 80 | 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 | 87 | check( |
| 82 | 88 | jmap, |
| 83 | 89 | "{\n" | ... | ... |