gpt4 book ai didi

python - 使用python编写json文件

转载 作者:太空宇宙 更新时间:2023-11-04 06:49:46 25 4
gpt4 key购买 nike

<分区>

我正在尝试使用 python 脚本读取和写入 json 文件(我已将此 python block 嵌入到 shell 脚本中)

测试.json

{
"environments": ["dev", "qa", "load", "prod"],
"region": ["asia", "europe", "americas", "asia-pacific"],
"product": ["mobile", "internet", "kiosk", "branch"],
"ID": ["mobile:111", "internet:222", "kiosk:333", "branch:444"]
}

我正在尝试添加地区(英国),在此之前我想检查并添加它是否在列表中不可用。下面是我的 python 代码,我可以更新值

reg_val="uk"

a_dict = {}
try:
with open('test.json') as data_file:
data = json.load(data_file)
temp_list = []
for dicObj in data["region"]:
temp_list.append(dicObj)
temp_list.append(reg_val)
data["region"] = temp_list
a_dict["region"] = data["region"]
with open('test.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

我能够更新 json 文件,但它删除了其他列表。我看到的输出是

{
"region": [
"asia",
"europe",
"americas",
"asia-pacific",
"uk"
]
}

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