gpt4 book ai didi

python - 通过 python 代码附加 JSON 文件

转载 作者:太空宇宙 更新时间:2023-11-04 00:36:23 24 4
gpt4 key购买 nike

我正在尝试创建一个函数,将数据追加到 json 文件中,然后使用已经存在的相同缩进。我创建了如下所示的 json 文件。

{
"TableA":
[
{"ID": "10001", "Name": "Chandan","Age": "29"},
{"ID": "10002", "Name": "Rajesh", "Age": "24"},
{"ID": "10003", "Name": "Raju", "Age": "25"}
]
}

Python 代码:

import json

# Write Data on Json file
a_dict = {"ID": "10005", "Name": "Manoj","Age": "31"}
try:
with open('TableA.json', 'a') as f:
json_obj = json.dump(a_dict, json.load(f),ensure_ascii=False)
f.write(json_obj)
f.close()
except IOError as io:
print "ERROR: ", io


# Read data from Json File
with open('TableA.json') as data_file:
data = json.load(data_file)

for i in data["TableA"]:
print "ID: \t", i["ID"]
print "Name: \t", i["Name"]
print "Age: \t", i["Age"]

最佳答案

我做了一些更改以获得正确的输出。如果有人帮助我优化代码,请为此提供帮助。

import json

# Write Data
a_dict = {}
try:
with open('TableA.json') as data_file:
data = json.load(data_file)
temp_list = []
for dicObj in data["TableA"]:
temp_list.append(dicObj)
temp_list.append({"ID": "10006", "Name": "Ritesh","Age": "21"})
data["TableA"] = temp_list
a_dict["TableA"] = data["TableA"]
with open('TableA.json','w') as f:
f.write(json.dumps(a_dict, indent=4, sort_keys=True, encoding="utf-8"))
except IOError as io:
print "ERROR: ", io

# Read data from Json File
with open('TableA.json') as data_file:
data = json.load(data_file)

for i in data["TableA"]:
print "ID: \t", i["ID"]
print "Name: \t", i["Name"]
print "Age: \t", i["Age"]

输出:

 {
"TableA": [
{
"Age": "29",
"ID": "10001",
"Name": "Chandan"
},
{
"Age": "24",
"ID": "10002",
"Name": "Rajesh"
},
{
"Age": "25",
"ID": "10003",
"Name": "Raju"
},
{
"Age": "31",
"ID": "10005",
"Name": "Manoj"
},
{
"Age": "21",
"ID": "10004",
"Name": "Ritesh"
},
{
"Age": "21",
"ID": "10006",
"Name": "Ritesh"
}
]
}

关于python - 通过 python 代码附加 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43869140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com