【问题标题】:How to append data into a json key using python如何使用python将数据附加到json键中
【发布时间】:2022-01-06 23:21:13
【问题描述】:

我需要将数据添加到具有以下结构的 json 文件中的文档键中

{
  "inputDocuments": {
    "gcsDocuments": {
      "documents": [
        {
          "gcsUri": "gs://test/.PDF",
          "mimeType": "application/pdf"
        }
      ]
    }
  },
  "documentOutputConfig": {
    "gcsOutputConfig": {
      "gcsUri": "gs://test"
    }
  },
  "skipHumanReview": false

最终的输出应该是这样的

{
      "inputDocuments": {
        "gcsDocuments": {
          "documents": [
            {
              "gcsUri": "gs://test/FFL.PDF",
              "mimeType": "application/pdf"
            },
            {
              "gcsUri": "gs://test/BGF.PDF",
              "mimeType": "application/pdf"
            }
          ]
        }
      },
      "documentOutputConfig": {
        "gcsOutputConfig": {
          "gcsUri": "gs://test"
        }
      },
      "skipHumanReview": false

我已经尝试使用下面的代码创建一个脚本,但是在尝试添加数据并且它没有以正确的格式附加数据时遇到 Keyerror

# Python program to update
# JSON
import json

# function to add to JSON
def write_json(new_data, filename='keyvalue.json'):
    with open(filename,'r+') as file:
        # First we load existing data into a dict.
        file_data = json.load(file)
        # Join new_data with file_data inside emp_details
        file_data["documents"].append(new_data)
        # Sets file's current position at offset.
        file.seek(0)
        # convert back to json.
        json.dump(file_data, file, indent = 4)

    # python object to be appended
y = {
          "gcsUri": "gs://test/.PDF",
          "mimeType": "application/pdf"        
    }
    
write_json(y)

【问题讨论】:

    标签: python json gsutil


    【解决方案1】:

    您的documents 位于gcsDocuments 字典内,该字典位于inputDocuments 字典内(尝试print(file_data.keys()),即将其更改为

    file_data["inputDocuments"]["gcsDocuments"]["documents"].append(new_data)

    【讨论】:

      猜你喜欢
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-16
      • 2020-10-21
      • 1970-01-01
      • 2022-01-07
      • 2020-03-06
      • 2017-09-22
      相关资源
      最近更新 更多