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相同的结构中?意思是,我现在得到一个额外的不需要的'},{‘
示例只是为了显示问题,而不是实际的代码。
发布于 2022-05-10 10:28:15
将代码更改为:
data['site1'][0]['sw3'] = {"device_type": "cisco_ios", "host": "sw3.tpo.local"}因为现在您指定了在哪里准确地放置这个数据集。
https://stackoverflow.com/questions/72184541
复制相似问题