通过python-cod附加JSON文件

2024-05-13 15:03:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Python代码:

^{pr2}$

Tags: 文件数据函数代码nameidjsonage
2条回答

为了得到合适的输出,我做了一些改变。如果有人帮我优化代码,那么请帮我。在

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"]

输出:

^{pr2}$

您也可以选择重新编写整个json,而不是只追加一行。在

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))

相关问题 更多 >