GroupDocs.Assembly for Python via .NET enables you to generate documents directly from JSON data sources. The JsonDataSource class parses JSON and makes it available to your templates, supporting both simple and complex JSON structures.
Here are the steps to generate documents from JSON:
Create or obtain JSON data (from a file, an API response, or a string)
Instantiate JsonDataSource with the JSON file’s path, or with a binary stream holding the JSON text
Create a template document with expression tags referencing JSON properties
Use DocumentAssembler to assemble the template with JsonDataSource
Save the assembled document
Note
JsonDataSource automatically recognizes JSON types (numbers, booleans, dates, strings) and makes them available with proper types in templates, enabling numeric operations and date formatting. You can also read JSON with Python’s json module and pass the resulting dicts and lists, as shown in Generate from Custom Objects; then the JSON’s strings stay strings, and a date must be turned into a datetime in Python.
JsonDataSource reads a file path or a stream, and a str is always taken as a path. To use JSON text you already hold in memory, wrap its UTF-8 bytes in io.BytesIO:
You can configure how JsonDataSource parses JSON. The file below has one root property, accounts, holding an array, and account codes with leading zeros:
fromgroupdocs.assemblyimportDataSourceInfo,DocumentAssemblerfromgroupdocs.assembly.dataimportJsonDataLoadOptions,JsonDataSource,JsonSimpleValueParseModeoptions=JsonDataLoadOptions()options.always_generate_root_object=True# Always create root objectoptions.simple_value_parse_mode=JsonSimpleValueParseMode.STRICT# Strict type parsingjson_data_source=JsonDataSource("trade-accounts.json",options)assembler=DocumentAssembler()assembler.assemble_document("trade-account-list.docx","trade-account-list-report.docx",DataSourceInfo(json_data_source,"data"))
The template reaches the array through the root object:
<<foreach [in data.accounts]>>
<<[name]>> (account <<[code]>>), managed by <<[manager]>>
<</foreach>>
With JsonSimpleValueParseMode.STRICT, a JSON string stays a string, so the account code "0142" is written as 0142. In the default LOOSE mode, a string that looks like a number becomes a number, and the same tag writes 142.
Warning
By default, if a root JSON element is an object with only one property that is an object or array, the engine skips the root object. Set always_generate_root_object to True to always include it. Without it, data above is the array itself, and data.accounts fails with “Can not get the value of member ‘accounts’”.
Advanced Usage Topics
To learn more about working with complex JSON structures, date-time parsing, and advanced JsonDataSource options, please refer to the advanced usage section.
More resources
GitHub Examples
You may easily run the code above and see the feature in action in our GitHub examples: