Putting a document away and getting it back
Converting a PDF takes seconds and a large one takes minutes. Doing it twice is a waste, and the document object was designed to be written to a file and read back exactly.
from pathlib import Path
from docling.document_converter import DocumentConverter
document = DocumentConverter().convert("refunds.html").document
document.save_as_json(Path("refunds.json"))
print(Path("refunds.json").read_text()[:60])A plain JSON file that opens by naming its schema and the version of it. Further in are the same lists you read in lesson 5, with the addresses written out as strings; that is how the links between pieces survive the trip to disk.
Back into a document
from docling_core.types.doc import DoclingDocument
same = DoclingDocument.load_from_json(Path("refunds.json"))
print(same.export_to_markdown() == document.export_to_markdown())
print(len(same.tables), "tables")Everything is there, including the table grid and the cell spans from lesson 8. This is the only export in the course that loses nothing: Markdown loses spans, plain text loses the labels, and neither can be turned back into a document.
Docling reads its own JSON
The saved file is a supported input format in its own right, so a converter will take it.
result = DocumentConverter().convert("refunds.json")
print(result.input.format)
print(result.document.texts[0].text)That means a pipeline can convert once, store the JSON, and let everything downstream read the cheap file instead of the expensive one. For the handbook in lesson 28 it is the difference between a rebuild that takes seconds and one that reconverts the PDF every time.
The dictionary, without the file
as_dict = document.export_to_dict()
print(sorted(as_dict)[:6])
print(as_dict["texts"][0]["text"])Same content, no file. Useful when the document is going into a database or over a network rather than onto disk.
- Save the Markdown document as JSON, load it back, and compare the number of groups.
- Open
refunds.jsonand find the cell spans inside the table. - Call
document.save_as_markdown(Path("refunds.md"))and convert that file again; the round trip is not lossless and you can see where.
This is what real progress feels like.