You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js使用docx库遇TypeError: 无法将null转为对象的问题求助

问题:docx库中判断bab字段为null时不生成段落触发TypeError错误

我想实现当JSON数据中bab字段值为null时,不生成babParagraph段落,但用下面的条件判断代码时,触发了TypeError: Cannot convert undefined or null to object错误。使用的是docx库,Node.js版本为v20.11.1。

代码片段

let babParagraph = null; // 初始化babParagraph为null

// 判断item.bab是否不为null
if (item.bab !== null) {
    // 若不为null则创建babParagraph
    babParagraph = new Paragraph({
        children: [
            new docx.TextRun({
                text: 'Bab ' + item.bab,
            }),
            new docx.TextRun({
                text: '\nKetentuan Umum',
                break: 1,
            }),
        ],
        alignment: AlignmentType.CENTER,
    });
}

错误信息

var _name = Object.keys(value)[0];
                           ^
TypeError: Cannot convert undefined or null to object
 at Function.keys (<anonymous>)
    at d:\magang\json_ke_word\node_modules\docx\build\index.cjs:18745:32 
    at Array.forEach (<anonymous>)
    at resolve (d:\magang\json_ke_word\node_modules\docx\build\index.cjs:18743:16)
    at d:\magang\json_ke_word\node_modules\docx\build\index.cjs:18749:28 
    at Array.forEach (<anonymous>)
    at resolve (d:\magang\json_ke_word\node_modules\docx\build\index.cjs:18743:16)
    at d:\magang\json_ke_word\node_modules\docx\build\index.cjs:18749:28 
    at Array.forEach (<anonymous>)
    at resolve (d:\magang\json_ke_word\node_modules\docx\build\index.cjs:18743:16)

Node.js v20.11.1

JSON结构

{
    "bab": "II",
    "number": "",
    "part": null,
    "paragraph": null,
    "pasal": "pasal-2",
    "ref": null,
    "type": "",
    "content": ".",
    "additional_context": [],
    "context": ""
  },
  {
    "bab": null, // 当bab为null时,不显示babParagraph
    "number": "",
    "part": null,
    "paragraph": null,
    "pasal": "pasal-2",
    "ref": null,
    "type": "",
    "content": ".",
    "additional_context": [],
    "context": ""
  }

解决方案

问题根源

你把babParagraph初始化为null后,大概率是直接将这个null值传入了docx文档的段落列表中。docx库在处理段落集合时,会尝试遍历每个元素并调用Object.keys(),遇到null时就会触发该错误。

修复方法

不要将null值加入文档的段落数组,仅在item.bab不为null时,才生成并添加对应的babParagraph:

单条数据处理示例

// 初始化段落数组,只存放有效元素
const paragraphList = [];

// 仅当bab字段不为null时,创建并添加段落
if (item.bab !== null) {
    const babParagraph = new Paragraph({
        children: [
            new docx.TextRun({ text: 'Bab ' + item.bab }),
            new docx.TextRun({ text: '\nKetentuan Umum', break: 1 }),
        ],
        alignment: AlignmentType.CENTER,
    });
    paragraphList.push(babParagraph);
}

// 添加其他必要段落
paragraphList.push(
    new Paragraph({
        children: [new docx.TextRun(item.content)],
    })
);

// 构建文档
const doc = new docx.Document({
    sections: [{ children: paragraphList }],
});

多条数据循环处理示例

const allParagraphs = [];

// 遍历所有JSON数据
items.forEach(item => {
    // 处理bab段落:仅当bab不为null时生成
    if (item.bab !== null) {
        const babParagraph = new Paragraph({
            children: [
                new docx.TextRun({ text: 'Bab ' + item.bab }),
                new docx.TextRun({ text: '\nKetentuan Umum', break: 1 }),
            ],
            alignment: AlignmentType.CENTER,
        });
        allParagraphs.push(babParagraph);
    }

    // 处理内容段落
    const contentPara = new Paragraph({
        children: [new docx.TextRun(item.content)],
    });
    allParagraphs.push(contentPara);
});

// 创建最终文档
const doc = new docx.Document({
    sections: [{ children: allParagraphs }],
});

额外提醒

  • 永远不要把null或undefined传入docx库的元素集合(比如sections的children数组),库的内部逻辑不支持处理这些无效值
  • 可以提前过滤掉bab为null的数据,或者在构建文档结构时做条件判断,只添加有效元素

内容的提问来源于stack exchange,提问作者Gaga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 22:27:52