How to Convert JSON to Word in Python (JSON to DOCX)

Convert JSON data to Word documents in Python

JSON is one of the most common formats for exchanging structured data between applications, APIs, and databases. In many business scenarios, however, JSON data needs to be transformed into human-readable Word documents such as reports, invoices, summaries, contracts, or exported records.

Converting JSON to Word is not a simple file format conversion. JSON has no inherent Word structure, so the process requires parsing the JSON data and mapping its elements to appropriate Word document components such as paragraphs, tables, and headings.

This article demonstrates how to convert JSON data into Word documents in Python using Spire.Doc for Python. We'll cover multiple approaches, including exporting JSON as formatted text, creating Word tables from JSON arrays, and generating structured reports from nested JSON data.

Content Overview

  1. Understanding JSON-to-Word Conversion
  2. Install Spire.Doc for Python
  3. Method 1: Convert JSON to Word as Formatted Text
  4. Method 2: Convert JSON Arrays to Word Tables
  5. Method 3: Generate Structured Word Reports from JSON
  6. Handle Nested JSON Objects
  7. Handle Missing or Optional Fields
  8. Convert JSON Files to Word Documents
  9. Why Use Spire.Doc for JSON-to-Word Conversion
  10. FAQ
  11. Conclusion

1. Understanding JSON-to-Word Conversion

JSON and Word documents serve fundamentally different purposes. JSON is a structured data format designed for data exchange and machine processing, while Word documents are intended for human consumption with rich formatting, visual hierarchy, and page layout.

As a result, converting JSON to Word is not a direct format transformation. The JSON data must first be parsed and mapped to appropriate document elements before a Word document can be generated.

The conversion process typically follows this workflow:

JSON Data
      ↓
Parse JSON (json.loads)
      ↓
Map Data Structure
      ↓
Spire.Doc for Python
      ↓
Paragraphs / Tables / Headings
      ↓
DOCX Document

In Python, the built-in json module is commonly used to parse JSON data, while Spire.Doc for Python handles document generation. After the JSON structure is analyzed and mapped, Spire.Doc can create paragraphs, tables, headings, images, and other Word elements programmatically, producing a fully formatted DOCX document.

The table below shows common mappings between JSON structures and Word elements:

JSON Structure Word Element Example
Key-Value Pair Paragraph "Name": "John"Name: John
Array Table [{...}, {...}] → rows and columns
Object Section Nested object → grouped content
Title Field Heading "title": "Report" → Heading 1
URL/Image Path Image "logo": "img.png" → embedded image

Understanding these mappings is important because the same JSON data can be presented in different ways depending on the document's purpose. For example, simple key-value data may be exported as paragraphs, while collections of records are usually easier to read when rendered as tables. With Spire.Doc for Python, these mappings can be implemented programmatically to generate professional Word documents from structured JSON data.


2. Install Spire.Doc for Python

Before converting JSON to Word, you need to install Spire.Doc for Python in your development environment.

Install via pip (Recommended)

pip install spire.doc

Alternatively, you can download Spire.Doc for Python and integrate it manually.

After installation, import the library in your project:

from spire.doc import *
from spire.doc.common import *

3. Method 1: Convert JSON to Word as Formatted Text

This method is the simplest approach for converting JSON to Word. It works well for API responses, configuration files, and simple JSON exports where each key-value pair maps to a paragraph.

Sample JSON

{
  "Name": "John Smith",
  "Department": "Sales",
  "Country": "USA"
}

Python Code

import json
from spire.doc import Document, FileFormat, HorizontalAlignment

json_data = '{"Name": "John Smith", "Department": "Sales", "Country": "USA"}'
data = json.loads(json_data)

document = Document()
section = document.AddSection()

for key, value in data.items():
    paragraph = section.AddParagraph()
    text_range = paragraph.AppendText(f"{key}: {value}")
    text_range.CharacterFormat.FontSize = 12
    paragraph.Format.AfterSpacing = 6

document.SaveToFile("json_to_text.docx", FileFormat.Docx)
document.Close()

Output

The following Word document shows how JSON key-value pairs can be converted into formatted paragraphs.

JSON key-value pairs converted to Word paragraphs

When to Use This Approach

This method is best suited for:

  • Simple key-value JSON objects
  • API response exports
  • Configuration file documentation
  • Quick data snapshots

It is not ideal for large datasets or tabular data, where Method 2 (tables) provides better readability.

If your goal is to analyze, filter, or manipulate structured JSON data in a spreadsheet, you may also be interested in our guide on converting JSON to Excel in Python.


4. Method 2: Convert JSON Arrays to Word Tables

When JSON data contains arrays of objects, tables provide the most effective way to present the data in a Word document. This is the most common scenario for converting JSON to Word, as many APIs and databases return data as JSON arrays.

Sample JSON

[
  {"Product": "Laptop", "Price": 1200, "Stock": 45},
  {"Product": "Mouse", "Price": 30, "Stock": 200},
  {"Product": "Keyboard", "Price": 85, "Stock": 120}
]

Python Code

import json
from spire.doc import (
    Document, FileFormat, HorizontalAlignment,
    VerticalAlignment, TableRowHeightType, Color
)

json_data = '''[
  {"Product": "Laptop", "Price": 1200, "Stock": 45},
  {"Product": "Mouse", "Price": 30, "Stock": 200},
  {"Product": "Keyboard", "Price": 85, "Stock": 120}
]'''
data = json.loads(json_data)

document = Document()
section = document.AddSection()

if data:
    headers = list(data[0].keys())
    table = section.AddTable(True)
    table.ResetCells(len(data) + 1, len(headers))

    header_row = table.Rows[0]
    header_row.IsHeader = True
    header_row.Height = 20
    header_row.HeightType = TableRowHeightType.Exactly

    for col_index, header in enumerate(headers):
        header_row.Cells[col_index].CellFormat.Shading.BackgroundPatternColor = Color.get_Gray()
        header_row.Cells[col_index].CellFormat.VerticalAlignment = VerticalAlignment.Middle
        paragraph = header_row.Cells[col_index].AddParagraph()
        paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
        text_range = paragraph.AppendText(header)
        text_range.CharacterFormat.Bold = True
        text_range.CharacterFormat.FontSize = 12

    for row_index, record in enumerate(data):
        data_row = table.Rows[row_index + 1]
        data_row.Height = 20
        data_row.HeightType = TableRowHeightType.Exactly
        for col_index, key in enumerate(headers):
            data_row.Cells[col_index].CellFormat.VerticalAlignment = VerticalAlignment.Middle
            paragraph = data_row.Cells[col_index].AddParagraph()
            paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
            text_range = paragraph.AppendText(str(record.get(key, "")))
            text_range.CharacterFormat.FontSize = 11

document.SaveToFile("json_to_table.docx", FileFormat.Docx)
document.Close()

Output

The following screenshot shows the generated Word table created from the JSON array.

JSON array converted to Word table

Why Use Tables for JSON Arrays

Tables are the natural fit for JSON array data because:

  • Each JSON object maps to a table row
  • Each key maps to a column header
  • Data is aligned for easy scanning and comparison
  • Tables are the standard format for reports, inventory lists, and exported database records

Enhancing JSON Tables with Formatting

Unlike plain text exports, Spire.Doc allows JSON data to be rendered as professionally formatted Word tables. Beyond basic table creation, you can apply:

  • Table styles – Use DefaultTableStyle or ApplyStyle for consistent, polished table appearances
  • Borders and shading – Control cell borders, background colors, and alternating row colors
  • Alignment – Set horizontal and vertical alignment at the cell, row, or table level
  • Custom formatting – Apply font size, bold, and color to individual cells or ranges
  • Auto-fit behavior – Use AutoFit to adjust column widths to content or window size

These formatting capabilities transform raw JSON data into professional report layouts suitable for business documents, client deliverables, and automated reporting pipelines.

If you need to create more sophisticated Word tables, such as merged cells, custom table layouts, or advanced formatting, see our guide on creating and formatting tables in Word documents using Python.


5. Method 3: Generate Structured Word Reports from JSON

Real-world JSON data often contains a mix of metadata, summary text, and tabular data. This method combines headings, paragraphs, and tables to generate a complete structured Word report from JSON.

Sample JSON

{
  "title": "Monthly Sales Report",
  "period": "June 2026",
  "summary": "Total revenue reached $580,000 this month, representing a 12% increase over the previous period. All regions showed positive growth.",
  "sales": [
    {"Region": "North", "Revenue": 150000, "Units": 320},
    {"Region": "South", "Revenue": 120000, "Units": 280},
    {"Region": "East", "Revenue": 180000, "Units": 410},
    {"Region": "West", "Revenue": 130000, "Units": 290}
  ]
}

Python Code

import json
from spire.doc import (
    Document, FileFormat, HorizontalAlignment,
    VerticalAlignment, TableRowHeightType, Color,
    BuiltinStyle
)

json_data = '''{
  "title": "Monthly Sales Report",
  "period": "June 2026",
  "summary": "Total revenue reached $580,000 this month, representing a 12% increase over the previous period. All regions showed positive growth.",
  "sales": [
    {"Region": "North", "Revenue": 150000, "Units": 320},
    {"Region": "South", "Revenue": 120000, "Units": 280},
    {"Region": "East", "Revenue": 180000, "Units": 410},
    {"Region": "West", "Revenue": 130000, "Units": 290}
  ]
}'''
data = json.loads(json_data)

document = Document()
section = document.AddSection()

heading_style = document.AddStyle(BuiltinStyle.Heading1)
subheading_style = document.AddStyle(BuiltinStyle.Heading2)

title_para = section.AddParagraph()
title_para.ApplyStyle(heading_style.Name)
title_para.AppendText(data.get("title", "Report"))

period_para = section.AddParagraph()
period_para.AppendText(f"Period: {data.get('period', 'N/A')}")
period_para.Format.AfterSpacing = 12

summary_heading = section.AddParagraph()
summary_heading.ApplyStyle(subheading_style.Name)
summary_heading.AppendText("Executive Summary")

summary_para = section.AddParagraph()
summary_para.AppendText(data.get("summary", ""))
summary_para.Format.AfterSpacing = 12

sales_heading = section.AddParagraph()
sales_heading.ApplyStyle(subheading_style.Name)
sales_heading.AppendText("Sales Data")

sales = data.get("sales", [])
if sales:
    headers = list(sales[0].keys())
    table = section.AddTable(True)
    table.ResetCells(len(sales) + 1, len(headers))

    header_row = table.Rows[0]
    header_row.IsHeader = True
    header_row.Height = 20
    header_row.HeightType = TableRowHeightType.Exactly

    for col_index, header in enumerate(headers):
        header_row.Cells[col_index].CellFormat.Shading.BackgroundPatternColor = Color.get_Gray()
        header_row.Cells[col_index].CellFormat.VerticalAlignment = VerticalAlignment.Middle
        paragraph = header_row.Cells[col_index].AddParagraph()
        paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
        text_range = paragraph.AppendText(header)
        text_range.CharacterFormat.Bold = True

    for row_index, record in enumerate(sales):
        data_row = table.Rows[row_index + 1]
        data_row.Height = 20
        data_row.HeightType = TableRowHeightType.Exactly
        for col_index, key in enumerate(headers):
            data_row.Cells[col_index].CellFormat.VerticalAlignment = VerticalAlignment.Middle
            paragraph = data_row.Cells[col_index].AddParagraph()
            paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
            paragraph.AppendText(str(record.get(key, "")))

document.SaveToFile("json_report.docx", FileFormat.Docx)
document.Close()

Output

The generated Word document combines headings, descriptive text, and tabular data into a structured report, making the JSON data easier to read and share.

Structured Word report generated from JSON data

Key Techniques

This example demonstrates several important techniques for generating Word reports from JSON:

  • Headings – Use BuiltinStyle.Heading1 and Heading2 for document structure and table-of-contents compatibility
  • Paragraphs – Add summary and descriptive text between headings
  • Tables – Render JSON arrays as tabular data within the report
  • Combinations – Mix multiple Word element types in a single document

Why Structured Reports Matter

In business environments, JSON data rarely exists in isolation. It typically comes from APIs, databases, or reporting systems and needs to be transformed into documents that decision-makers can read, share, and archive. Common scenarios include:

  • Sales reports – Revenue, units, and regional breakdowns from CRM or ERP systems
  • Inventory reports – Stock levels, reorder alerts, and warehouse summaries
  • Customer summaries – Contact details, order history, and account status
  • Compliance reports – Audit logs, access records, and policy status
  • Automated reporting systems – Scheduled jobs that generate documents from JSON data and distribute them via email or document management systems

Spire.Doc makes it possible to transform structured JSON data into polished business documents automatically, combining headings, paragraphs, and tables in a single output.

If you need to build more sophisticated document layouts, such as multi-section reports, cover pages, tables of contents, headers, footers, or custom document templates, see our guide on creating structured Word documents in Python.


6. Handle Nested JSON Objects

Many real-world JSON responses contain nested objects. For example, a customer record may include an address object with its own fields. Handling these nested structures is essential for complete JSON-to-Word conversion.

Example JSON

{
  "customer": {
    "name": "Tom Wilson",
    "email": "tom@example.com",
    "address": {
      "street": "123 Main St",
      "city": "Springfield",
      "state": "IL"
    }
  }
}

Python Code

import json
from spire.doc import Document, FileFormat, HorizontalAlignment

def add_nested_object(section, obj, indent_level=0):
    for key, value in obj.items():
        if isinstance(value, dict):
            heading_para = section.AddParagraph()
            heading_text = "  " * indent_level + key.capitalize()
            text_range = heading_para.AppendText(heading_text)
            text_range.CharacterFormat.Bold = True
            text_range.CharacterFormat.FontSize = 12 - indent_level
            heading_para.Format.AfterSpacing = 4
            add_nested_object(section, value, indent_level + 1)
        else:
            paragraph = section.AddParagraph()
            label = "  " * indent_level + f"{key}: {value}"
            text_range = paragraph.AppendText(label)
            text_range.CharacterFormat.FontSize = 11
            paragraph.Format.AfterSpacing = 2

json_data = '''{
  "customer": {
    "name": "Tom Wilson",
    "email": "tom@example.com",
    "address": {
      "street": "123 Main St",
      "city": "Springfield",
      "state": "IL"
    }
  }
}'''
data = json.loads(json_data)

document = Document()
section = document.AddSection()

add_nested_object(section, data)

document.SaveToFile("json_nested.docx", FileFormat.Docx)
document.Close()

Output

The following screenshot shows the hierarchical Word document generated from the nested JSON structure.

Nested JSON converted to a hierarchical Word document

Nested JSON objects can be represented as hierarchical sections in a Word document, making complex data structures easier to read and navigate.

How It Works

The add_nested_object function recursively traverses the JSON structure:

  • When it encounters a dict value, it creates a bold heading for the key and recurses into the nested object
  • When it encounters a scalar value, it creates a paragraph with the key-value pair
  • The indent_level parameter controls indentation and font size to create a visual hierarchy

This recursive approach handles arbitrarily deep nesting and produces a readable hierarchical layout in the Word document.


7. Handle Missing or Optional JSON Fields

In real-world applications, JSON data from APIs and databases often contains missing or optional fields. Records may have inconsistent keys, and some fields may be absent entirely. Handling these cases gracefully prevents errors and ensures the generated Word document remains complete.

Example JSON with Missing Fields

[
  {"Name": "Tom Wilson", "Email": "tom@example.com", "Phone": "555-0100"},
  {"Name": "Jane Doe", "Email": "jane@example.com"},
  {"Name": "Bob Brown", "Phone": "555-0300"}
]

Python Code

import json
from spire.doc import (
    Document, FileFormat, HorizontalAlignment,
    VerticalAlignment, TableRowHeightType, Color
)

json_data = '''[
  {"Name": "Tom Wilson", "Email": "tom@example.com", "Phone": "555-0100"},
  {"Name": "Jane Doe", "Email": "jane@example.com"},
  {"Name": "Bob Brown", "Phone": "555-0300"}
]'''
data = json.loads(json_data)

document = Document()
section = document.AddSection()

if data:
    all_keys = []
    for record in data:
        for key in record.keys():
            if key not in all_keys:
                all_keys.append(key)

    table = section.AddTable(True)
    table.ResetCells(len(data) + 1, len(all_keys))

    header_row = table.Rows[0]
    header_row.IsHeader = True
    header_row.Height = 20
    header_row.HeightType = TableRowHeightType.Exactly

    for col_index, header in enumerate(all_keys):
        header_row.Cells[col_index].CellFormat.Shading.BackgroundPatternColor = Color.get_Gray()
        header_row.Cells[col_index].CellFormat.VerticalAlignment = VerticalAlignment.Middle
        paragraph = header_row.Cells[col_index].AddParagraph()
        paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
        text_range = paragraph.AppendText(header)
        text_range.CharacterFormat.Bold = True

    for row_index, record in enumerate(data):
        data_row = table.Rows[row_index + 1]
        data_row.Height = 20
        data_row.HeightType = TableRowHeightType.Exactly
        for col_index, key in enumerate(all_keys):
            data_row.Cells[col_index].CellFormat.VerticalAlignment = VerticalAlignment.Middle
            paragraph = data_row.Cells[col_index].AddParagraph()
            paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
            paragraph.AppendText(str(record.get(key, "N/A")))

document.SaveToFile("json_missing_fields.docx", FileFormat.Docx)
document.Close()

Output

The following screenshot shows the generated Word table, where missing fields are automatically filled with placeholder values to maintain a consistent document structure.

Word table generated from JSON data with missing fields

Key Techniques

  • dict.get(key, "N/A") – Returns a default value when a key is missing, preventing KeyError exceptions
  • Dynamic column collection – Iterates all records to build a complete set of column headers, ensuring no field is missed even when it appears in only some records
  • Consistent table structure – All rows have the same number of columns regardless of which fields are present in each record

This approach is essential for production use cases where API responses may vary in structure across different records or over time.


8. Convert JSON Files to Word Documents

In practice, JSON data often originates from files rather than inline strings. API export results, configuration files, database dumps, data exchange files, and log data are all commonly stored as .json files that need to be converted to Word documents.

The conversion process for JSON files follows this workflow:

JSON File (.json)
        ↓
Load JSON (json.load)
        ↓
Generate Word Document (Spire.Doc)
        ↓
DOCX Document

Python Code

import json
from spire.doc import Document, FileFormat

with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

document = Document()
section = document.AddSection()

# Process the loaded JSON data
# using any of the techniques shown in Methods 1–3
# (formatted text, tables, or structured reports)

document.SaveToFile("data_report.docx", FileFormat.Docx)
document.Close()

Key Points

  • json.load() reads and parses a JSON file directly, unlike json.loads() which parses a string
  • encoding="utf-8" ensures proper handling of non-ASCII characters in JSON files
  • Once the JSON file is loaded into a Python dictionary or list, Spire.Doc for Python can generate paragraphs, tables, or structured reports from the parsed data using any of the methods described earlier in this article

For complete examples of processing the loaded data, refer to Method 1 for formatted text, Method 2 for tables, or Method 3 for structured reports.


9. Why Use Spire.Doc for JSON-to-Word Conversion

Converting JSON to Word involves several practical challenges that go beyond simple data parsing. Generating properly formatted tables, applying consistent styles, creating structured reports with headings and paragraphs, and handling nested or incomplete data all require a capable document generation API.

Challenges of JSON-to-Word Conversion

  • Table generation – JSON arrays must be mapped to Word tables with headers, rows, and cell formatting
  • Document formatting – Raw data exports lack the visual hierarchy that makes Word documents readable
  • Structured reports – Combining headings, paragraphs, and tables in a single document requires coordinating multiple element types
  • Nested data – Deeply nested JSON objects need recursive traversal and hierarchical layout
  • Large documents – Generating multi-page reports from large JSON datasets demands efficient resource management

Benefits of Spire.Doc for Python

Spire.Doc for Python addresses these challenges with a straightforward API:

  • Create Word documents without Microsoft Word – No Office installation or Interop dependencies required
  • Generate paragraphs, tables, images, headers, and footers – Full coverage of Word document elements
  • Apply built-in and custom styles – Consistent formatting across documents using BuiltinStyle and ParagraphStyle
  • Automate report generation – Programmatically build structured reports from any JSON data source
  • Export to DOCX and other formats – Save to DOCX, PDF, HTML, RTF, and more using FileFormat

With Spire.Doc, the JSON-to-Word conversion process becomes a structured mapping from parsed data to Word elements, rather than manual string formatting or template manipulation.


10. FAQ

How do I convert JSON to Word in Python?

Parse the JSON data using Python's built-in json module, then use Spire.Doc for Python to create a Word document. Map JSON key-value pairs to paragraphs, JSON arrays to tables, and use headings for structure. See Method 1 for a basic example and Method 3 for a complete report.

Can JSON arrays be converted into Word tables?

Yes. JSON arrays of objects map naturally to Word tables, where each object becomes a row and each key becomes a column. See Method 2 for a complete code example that creates a formatted table from a JSON array.

How do I create a DOCX report from API JSON responses?

Fetch the API response as JSON, parse it, and use Spire.Doc for Python to generate the report. Combine headings for titles, paragraphs for summaries, and tables for data arrays. See Method 3 for a structured report example.

Can nested JSON objects be exported to Word?

Yes. Use a recursive function to traverse nested JSON objects, creating headings for object keys and paragraphs for scalar values. See Section 6 for a detailed example of handling nested structures with visual hierarchy.

How do I convert a JSON file to a Word document?

Use Python's json.load() to read the JSON file, then process the parsed data with Spire.Doc for Python. See Section 8 for a code example.

What is the best way to generate Word documents from JSON data?

The best approach depends on the JSON structure. For simple key-value data, use formatted paragraphs. For arrays, use tables. For complex nested data with mixed content, combine headings, paragraphs, and tables as shown in Method 3.


11. Conclusion

Generating Word documents from JSON data is a common requirement in reporting, document automation, and data export workflows. With Spire.Doc for Python, you can create paragraphs, tables, and structured document layouts directly from JSON, making it easier to produce professional DOCX files from application data.

The same approach can be extended to API responses, database records, configuration files, and other structured data sources, helping automate document generation in both small projects and enterprise systems.

For scenarios involving large documents or document conversion requirements, a licensed version is required.