通过python代码附加JSON文件 [英] Appending JSON file through python code
本文介绍了通过python代码附加JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个函数,该函数将数据附加到json文件中,并使用已经存在的相同缩进.我创建了json文件,如下所示.
I'm trying to create a function that would append data into json file follow with same indentation which is already exist. I created json file as given below.
{
"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"]
推荐答案
您也可以选择再次写入整个json,而不是仅添加一行.
Instead of appending only one line, you can also choose to write the whole json again.
with open('TableA.json') as data_file:
data = json.load(data_file)
a_dict = {"ID": "10005", "Name": "Manoj","Age": "31"}
new_data = data["TableA"].append(a_dict)
with open('TableA.json','w') as f:
f.write(json.dumps(new_data, indent=4, sort_keys=True))
这篇关于通过python代码附加JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文