From 948de609900745835656d4566a90fee64c5343da Mon Sep 17 00:00:00 2001 From: Jay Berkenbilt Date: Fri, 6 May 2022 19:04:20 -0400 Subject: Objects json: write incrementally and in numeric order The following script was used to adjust test data: ---------- #!/usr/bin/env python3 import json import sys import re def json_dumps(data): return json.dumps(data, ensure_ascii=False, indent=2, separators=(',', ': ')) for filename in sys.argv[1:]: with open(filename, 'r') as f: data = json.loads(f.read()) if 'objects' not in data: continue trailer = None to_sort = [] for k, v in data['objects'].items(): if k == 'trailer': trailer = v else: m = re.match(r'^(\d+) \d+ R', k) if m: to_sort.append([int(m.group(1)), k, v]) newobjects = {x[1]: x[2] for x in sorted(to_sort)} if trailer is not None: newobjects['trailer'] = trailer data['objects'] = newobjects print(json_dumps(data)) ---------- --- libqpdf/QPDFJob.cc | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) (limited to 'libqpdf/QPDFJob.cc') diff --git a/libqpdf/QPDFJob.cc b/libqpdf/QPDFJob.cc index 5621ef5e..63fa0c34 100644 --- a/libqpdf/QPDFJob.cc +++ b/libqpdf/QPDFJob.cc @@ -1044,20 +1044,23 @@ QPDFJob::getWantedJSONObjects() void QPDFJob::doJSONObjects(Pipeline* p, bool& first, QPDF& pdf) { + JSON::writeDictionaryKey(p, first, "objects", 0); + bool first_object = true; + JSON::writeDictionaryOpen(p, first_object, 1); bool all_objects = m->json_objects.empty(); std::set wanted_og = getWantedJSONObjects(); - JSON j_objects = JSON::makeDictionary(); - if (all_objects || m->json_objects.count("trailer")) { - j_objects.addDictionaryMember( - "trailer", pdf.getTrailer().getJSON(true)); - } std::vector objects = pdf.getAllObjects(); for (auto& obj: objects) { if (all_objects || wanted_og.count(obj.getObjGen())) { - j_objects.addDictionaryMember(obj.unparse(), obj.getJSON(true)); + JSON::writeDictionaryItem( + p, first_object, obj.unparse(), obj.getJSON(true), 1); } } - JSON::writeDictionaryItem(p, first, "objects", j_objects, 0); + if (all_objects || m->json_objects.count("trailer")) { + JSON::writeDictionaryItem( + p, first_object, "trailer", pdf.getTrailer().getJSON(true), 1); + } + JSON::writeDictionaryClose(p, first_object, 1); } void @@ -1090,8 +1093,7 @@ QPDFJob::doJSONObjectinfo(Pipeline* p, bool& first, QPDF& pdf) void QPDFJob::doJSONPages(Pipeline* p, bool& first, QPDF& pdf) { - JSON::writeNext(p, first, 0); - *p << "\"pages\": "; + JSON::writeDictionaryKey(p, first, "pages", 0); bool first_page = true; JSON::writeArrayOpen(p, first_page, 1); QPDFPageDocumentHelper pdh(pdf); -- cgit v1.2.3-54-g00ecf