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

如何使用Python向JSON文件指定层级的documents键数组追加数据

问题原因

你出现KeyError的核心原因是没有按JSON的嵌套层级定位到documents数组:documents并不是根节点下的直接键,而是嵌套在inputDocuments → gcsDocuments两级节点下的,直接访问根节点的documents自然会找不到对应键。

修正后的完整代码

调整点如下:

  1. 修正数组定位路径,按嵌套层级找到目标数组
  2. 补充文件截断逻辑,避免旧文件内容比新内容长时,末尾残留多余字符导致JSON格式错误
  3. 待追加的条目同步调整为你需求里的BGF.PDF
import json

def write_json(new_data, filename='keyvalue.json'):
    with open(filename,'r+') as file:
        # 加载现有JSON数据
        file_data = json.load(file)
        # 按嵌套路径定位到documents数组后追加新数据
        file_data["inputDocuments"]["gcsDocuments"]["documents"].append(new_data)
        # 如需把原有第一个PDF路径改成示例中的FFL.PDF,可取消注释下面这行
        # file_data["inputDocuments"]["gcsDocuments"]["documents"][0]["gcsUri"] = "gs://test/FFL.PDF"
        # 指针移到文件开头
        file.seek(0)
        # 写入新的JSON数据
        json.dump(file_data, file, indent = 4)
        # 截断文件,删除新内容之后的残留旧数据
        file.truncate()

# 待追加的PDF条目
y = {
    "gcsUri": "gs://test/BGF.PDF",
    "mimeType": "application/pdf"        
}
    
write_json(y)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 00:36:04