如何使用 python 将数据附加到 json 键中
How to append data into a json key using python
我需要将数据添加到具有以下结构的 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)
您的 documents
在 gcsDocuments
字典中,而在 inputDocuments
字典中(尝试 print(file_data.keys()
),即将其更改为
file_data["inputDocuments"]["gcsDocuments"]["documents"].append(new_data)
我需要将数据添加到具有以下结构的 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)
您的 documents
在 gcsDocuments
字典中,而在 inputDocuments
字典中(尝试 print(file_data.keys()
),即将其更改为
file_data["inputDocuments"]["gcsDocuments"]["documents"].append(new_data)