[英]Issue writing to JSON-file with Python
JSON文件
{
"site1": [
{
"sw1": {
"device_type": "cisco_ios",
"host": "sw1.test.local"
},
"sw2": {
"device_type": "cisco_ios",
"host": "sw2.test.local"
}
}
]
}
代碼:
import json
def write_json(data, filename='data.json'):
with open(filename, "w") as f:
json.dump(data, f, indent=2)
def collect_new_data():
with open('data.json') as json_file:
data = json.load(json_file)
temp = data['site1']
new_data = {'sw3': {"device_type": "cisco_ios", "host": "sw3.tpo.local"}}
temp.append(new_data)
return data
the_data = collect_new_data()
write_json(the_data)
結果:
{
"site1": [
{
"sw1": {
"device_type": "cisco_ios",
"host": "sw1.test.local"
},
"sw2": {
"device_type": "cisco_ios",
"host": "sw2.test.local"
}
},
{
"sw3": {
"device_type": "cisco_ios",
"host": "sw3.tpo.local"
}
}
]
}
Python/JSON 的新手,盡力而為。
到問題。 如何使它附加到與 sw1 和 sw2 相同的結構中? 意思是,我現在得到一個額外不需要的 '},{'
例子只是為了展示問題,而不是實際的代碼。
將您的代碼更改為:
data['site1'][0]['sw3'] = {"device_type": "cisco_ios", "host": "sw3.tpo.local"}
因為現在你指定了把字典放在哪里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.