From 37105710ee0b332a3020d4b3220c95b8f4267555 Mon Sep 17 00:00:00 2001 From: Jay Berkenbilt Date: Wed, 19 Jan 2022 09:31:28 -0500 Subject: Implement JSONHandler for recursively processing JSON --- libtests/json.cc | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) (limited to 'libtests/json.cc') diff --git a/libtests/json.cc b/libtests/json.cc index 7bea5589..006f00cf 100644 --- a/libtests/json.cc +++ b/libtests/json.cc @@ -1,7 +1,7 @@ #include #include #include -#include +#include static void check(JSON const& j, std::string const& exp) { @@ -20,12 +20,25 @@ static void test_main() "\\u0003\\t\\b\\r\\n<4>\""); JSON jnull = JSON::makeNull(); check(jnull, "null"); + assert(jnull.isNull()); + std::string value; + assert(! jnull.getNumber(value)); JSON jarr = JSON::makeArray(); check(jarr, "[]"); JSON jstr2 = JSON::makeString("a\tb"); + assert(jstr2.getString(value)); + assert(value == "a\tb"); + assert(! jstr2.getNumber(value)); JSON jint = JSON::makeInt(16059); JSON jdouble = JSON::makeReal(3.14159); JSON jexp = JSON::makeNumber("2.1e5"); + JSON jbool1 = JSON::makeBool(true); + JSON jbool2 = JSON::makeBool(false); + bool bvalue = false; + assert(jbool1.getBool(bvalue)); + assert(bvalue); + assert(jbool2.getBool(bvalue)); + assert(! bvalue); jarr.addArrayElement(jstr2); jarr.addArrayElement(jnull); jarr.addArrayElement(jint); @@ -39,6 +52,18 @@ static void test_main() " 3.14159,\n" " 2.1e5\n" "]"); + std::vector avalue; + assert(jarr.forEachArrayItem([&avalue](JSON j) { + avalue.push_back(j.unparse()); + })); + std::vector xavalue = { + "\"a\\tb\"", + "null", + "16059", + "3.14159", + "2.1e5", + }; + assert(avalue == xavalue); JSON jmap = JSON::makeDictionary(); check(jmap, "{}"); jmap.addDictionaryMember("b", jstr2); @@ -73,6 +98,18 @@ static void test_main() check(QPDFObjectHandle::newReal(".34").getJSON(), "0.34"); check(QPDFObjectHandle::newReal("-0.56").getJSON(), "-0.56"); check(QPDFObjectHandle::newReal("-.78").getJSON(), "-0.78"); + JSON jmap2 = JSON::parse(R"({"a": 1, "b": "two", "c": [true]})"); + std::map dvalue; + assert(jmap2.forEachDictItem([&dvalue] + (std::string const& k, JSON j) { + dvalue[k] = j.unparse(); + })); + std::map xdvalue = { + {"a", "1"}, + {"b", "\"two\""}, + {"c", "[\n true\n]"}, + }; + assert(dvalue == xdvalue); } static void check_schema(JSON& obj, JSON& schema, bool exp, -- cgit v1.2.3-54-g00ecf