I am trying to read and write a json file using python script(I have embedded this python block inside a shell script)
test.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"] }
I am trying to add region(uk), before that I want to check and add if it is not avilable in list. Below is my python code and I am able to update the value
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
I was able to update the json file, but it removes the other lists.The output I see is
{
"region": [
"asia",
"europe",
"americas",
"asia-pacific",
"uk"
]
}