Word 文档与 JSON 分别服务于截然不同的场景:前者面向人类阅读,后者面向程序消费。将 Word 转为 JSON,本质是一次结构映射------把段落、表格、标题等文档组件翻译成键值对与数组。本文从实际需求出发,介绍三种不同粒度的转换方式,并说明各自的适用边界。
环境准备
开始之前,需要安装对应的文档处理库:
bash
pip install spire.doc
该库支持 .doc 与 .docx 格式的读写,且运行时不要求本机安装 Office。下文示例均使用同一份 Word 文档进行演示,你可以根据实际文件调整路径。需要注意,涉及结构遍历与类型判断的代码中,除了 spire.doc,还需同时导入 spire.doc.common,后者提供了 Paragraph、Table 等类型,缺省会导致 isinstance 判断无法进行。
方法一:提取段落文本为 JSON 数组
最直接的转换方式是将文档中的每个段落提取为字符串,组成 JSON 数组。这种方式适合全文索引、文本向量化等场景,下游系统只需处理纯文本,无需关心文档结构。
核心思路是遍历文档的节(Section)与段落(Paragraph),过滤空段落,再将结果序列化。Word 文档本身是层级结构:一个文档包含若干节,每节包含若干段落,逐层遍历可以灵活控制提取范围。
python
import json
from spire.doc import Document
from spire.doc.common import *
input_file = "项目报告.docx"
output_file = "paragraphs.json"
document = Document()
document.LoadFromFile(input_file)
paragraphs = []
for i in range(document.Sections.Count):
section = document.Sections.get_Item(i)
for j in range(section.Paragraphs.Count):
paragraph = section.Paragraphs.get_Item(j)
text = paragraph.Text
if text.strip():
paragraphs.append(text)
document.Close()
result = {
"source": input_file,
"paragraph_count": len(paragraphs),
"paragraphs": paragraphs
}
with open(output_file, "w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
输出结果形如:
json
{
"source": "项目报告.docx",
"paragraph_count": 3,
"paragraphs": [
"季度销售报告",
"本文档概述了各区域的销售业绩情况。",
"华东区域表现优于预期。"
]
}
这一方法的局限也很明显:标题、正文、列表项在输出中没有任何区分,文档的层级信息完全丢失。如果后续处理需要识别内容类型,就需要采用更精细的策略。
方法二:将 Word 表格转为 JSON 对象数组
在报表、发票、产品清单等文档中,表格往往承载着最有价值的结构化数据。Word 表格天然具有行列结构,第一行通常为列标题,后续行为数据记录,这与 JSON 对象数组的映射关系非常自然。
以下代码遍历文档中的所有表格,以首行作为字段名,将每一数据行转换为一个 JSON 对象。相比逐个单元格硬编码取值,这里对列数与表头长度不一致的情况做了兜底,超出表头范围的列会以 Column_{c} 命名,避免索引越界。
python
import json
from spire.doc import Document
from spire.doc.common import *
input_file = "销售数据.docx"
output_file = "tables.json"
document = Document()
document.LoadFromFile(input_file)
all_tables = []
for i in range(document.Sections.Count):
section = document.Sections.get_Item(i)
for t in range(section.Tables.Count):
table = section.Tables.get_Item(t)
rows_data = []
if table.Rows.Count < 2:
continue
header_row = table.Rows[0]
headers = []
for c in range(header_row.Cells.Count):
cell_text = header_row.Cells[c].Paragraphs[0].Text.strip()
headers.append(cell_text)
for r in range(1, table.Rows.Count):
row = table.Rows[r]
row_dict = {}
for c in range(row.Cells.Count):
cell_text = row.Cells[c].Paragraphs[0].Text.strip()
row_dict[headers[c] if c < len(headers) else f"Column_{c}"] = cell_text
rows_data.append(row_dict)
all_tables.append({
"table_index": t,
"headers": headers,
"row_count": len(rows_data),
"rows": rows_data
})
document.Close()
result = {
"source": input_file,
"table_count": len(all_tables),
"tables": all_tables
}
with open(output_file, "w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
当文档的核心内容是表格时,这种方法输出的 JSON 可以直接导入数据库或数据分析工具,省去手动解析文本的步骤。row_count 字段同时也便于快速判断某张表是否为空表。
方法三:保留文档结构的层级化 JSON
前两种方法各取一端:一个只拿文本,一个只拿表格。如果目标是为 RAG 管道或知识库构建准备数据,更合理的做法是保留文档的原始顺序与内容类型,让标题、段落、表格在 JSON 中各得其所。
section.Body.ChildObjects 接口可以按文档顺序返回所有元素,而非分别遍历段落集合或表格集合。这意味着标题与其下方正文的关联关系可以被保留下来。
实现时,通过段落的 StyleName 判断是否为标题,并映射出标题级别。需要注意的是,Word 的标题样式名可能因模板或语言设置而异(如 Heading1、Heading 1 或中文的 标题 1),因此在实际项目中,查找前对样式名做规范化处理更为稳妥。
python
import json
from spire.doc import *
from spire.doc.common import *
input_file = "项目报告.docx"
output_file = "structured_output.json"
HEADING_STYLES = {
"Heading1": 1,
"Heading2": 2,
"Heading3": 3,
"Heading4": 4,
}
def get_heading_level(style_name):
return HEADING_STYLES.get(style_name, None)
def extract_table_data(table):
rows_data = []
if table.Rows.Count < 1:
return {"headers": [], "rows": []}
header_row = table.Rows[0]
headers = []
for c in range(header_row.Cells.Count):
headers.append(header_row.Cells[c].Paragraphs[0].Text.strip())
for r in range(1, table.Rows.Count):
row = table.Rows[r]
row_dict = {}
for c in range(row.Cells.Count):
cell_text = row.Cells[c].Paragraphs[0].Text.strip()
row_dict[headers[c] if c < len(headers) else f"Column_{c}"] = cell_text
rows_data.append(row_dict)
return {"headers": headers, "rows": rows_data}
document = Document()
document.LoadFromFile(input_file)
sections_data = []
for i in range(document.Sections.Count):
section = document.Sections.get_Item(i)
content_items = []
for j in range(section.Body.ChildObjects.Count):
obj = section.Body.ChildObjects.get_Item(j)
if isinstance(obj, Paragraph):
text = obj.Text.strip()
if not text:
continue
heading_level = get_heading_level(obj.StyleName)
if heading_level:
content_items.append({
"type": "heading",
"level": heading_level,
"text": text
})
else:
content_items.append({
"type": "paragraph",
"text": text
})
elif isinstance(obj, Table):
table_data = extract_table_data(obj)
content_items.append({
"type": "table",
"row_count": len(table_data["rows"]),
"data": table_data
})
sections_data.append({
"section_index": i,
"content": content_items
})
document.Close()
result = {
"source": input_file,
"section_count": len(sections_data),
"sections": sections_data
}
with open(output_file, "w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
输出的 JSON 中,每个内容项都带有 type 字段,下游程序可以据此决定如何处理:标题用于分段(chunking),段落用于嵌入,表格用于结构化抽取。这种带类型的层级结构在构建 RAG 应用时尤其有用,因为按标题切分文档通常比按固定长度切分能获得更好的检索效果。
如何选择
三种方法并非替代关系,而是对应不同的问题。
- 如果只需要纯文本做搜索索引,方法一足够且简单;
- 如果文档的核心是表格数据,方法二能直接产出可入库的结构;
- 如果目标是保留文档语义结构以供下游智能处理,方法三的额外代码量是值得的。
实际项目中,也可以组合使用:先用方法三获取整体结构,再根据 type 字段分别处理各类元素。
无论选择哪种方式,json.dump 的 ensure_ascii=False 参数都建议保留,否则中文内容会被转义为 Unicode 编码,虽然不影响程序解析,但人工查看时会增加不必要的阅读负担。另外,若要在判断分支中使用 isinstance(obj, Paragraph) 与 isinstance(obj, Table),务必导入 spire.doc.common,否则这些类名不可用------这是一个容易忽略的细节。
几点注意事项
- 标题样式名差异 :不同模板或语言环境下,标题样式可能显示为
Heading1、Heading 1、标题 1等形式。若文档来源不固定,建议在get_heading_level中先做小写化与去空格处理,再查表。 - 合并单元格 :Word 表格中的合并单元格会影响行列索引与
Cells.Count,上述代码按原始行列读取,遇到复杂合并表时需额外处理。 - 空段落与页眉页脚 :
section.Paragraphs默认不包含页眉页脚内容;若需要提取这些区域,应单独访问section.HeadersFooters。 - 大文档的内存占用:一次性加载整份文档再序列化,对超大文件会带来内存压力。必要时可按节分批读取并分段写入 JSON。
总结
把 Word 文档转换为 JSON,并没有放之四海而皆准的单一写法,关键在于先明确下游要消费的是"文本"还是"结构"。只做全文检索或文本嵌入,段落数组即可满足;以表格数据为主,按表头映射为对象数组更实用;面向知识库或 RAG 管道,则应采用带 type 字段的层级结构以保留语义顺序。三种方式共享同一套基础 API------加载文档、按节遍历、读取段落与表格、序列化输出,差异只在于遍历粒度与字段组织。掌握这一脉络后,再根据具体文档中合并单元格、标题样式、页眉页脚等细节做针对性处理,就能得到与业务需求匹配的 JSON 输出。