Python在文件中附加json对象,如果对象不存在则保护

时间:2016-08-15 12:42:26

标签: python json

我正在使用python读取json文件,然后追加到对象中的数组中,其形状为

"additional_info": {"other_names": ["12.13"]

我按如下方式追加数组:

data["additional_info"]["other_names"].append('13.9')
with open('jsonfile', 'w') as f:
    json.dump(data, f)

我想设置一个警卫来检查json文件中是否存在additional_info和other_names,如果它没有创建它。我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

通常我会使用嵌套的try-except来检查每个缺失的密钥或defaultdict,但在这种情况下,为了简单起见,我认为我会使用2 if个语句:

if "additional_info" not in data:
    data["additional_info"] = {}
if "other_names" not in data["additional_info"]:
    data["additional_info"]["other_names"] = []

data["additional_info"]["other_names"].append('13.9')

with open('jsonfile', 'w') as f:
    json.dump(data, f)

两个用例:

data = {}

if "additional_info" not in data:
    data["additional_info"] = {}
if "other_names" not in data["additional_info"]:
    data["additional_info"]["other_names"] = []

data["additional_info"]["other_names"].append('13.9')

print(data)
>> {'additional_info': {'other_names': ['13.9']}}

并且

data = {"additional_info": {"other_names": ["12.13"]}}

if "additional_info" not in data:
    data["additional_info"] = {}
if "other_names" not in data["additional_info"]:
    data["additional_info"]["other_names"] = []

data["additional_info"]["other_names"].append('13.9')

print(data)
>> {'additional_info': {'other_names': ['12.13', '13.9']}}