python - 如何在 JSON 中有另一个值数据?
问题描述
我有以下列表:
label_list_SR1 = ['17011', '17022']
label_list_SR2 = ['18011', '18022', '18033']
一、JSON内容
我使用RESTCONF从路由器返回的以下 JSON 内容:
{
"Cisco-IOS-XE-native:name": [
{
"pname": "SR1",
"mode": "enable",
"index": [
{
"idx": 1,
"next-label": 17011
},
{
"idx": 2,
"next-label": 17022
}
]
},
{
"pname": "SR2",
"mode": "enable",
"index": [
{
"idx": 1,
"next-label": 18022
},
{
"idx": 2,
"next-label": 18033
},
{
"idx": 3,
"next-label": 18044
}
]
}
]
}
二、构建 JSON 文件
该函数make_json(label_list, SR_path)
构建一个 JSON 文件data.json
,以便将其发送到下一个函数。
def make_json(label_list, SR_path):
key_1 = 'Cisco-IOS-XE-native:explicit-path'
key_2 = "name"
key_2_1 = "pname"
key_2_2 = "mode"
key_2_3 = "index"
data = {
key_1: {
key_2: [
{
key_2_1: SR_path,
key_2_2: "enable",
key_2_3: [
{
"idx": 1,
"next-label": 22
}
]
}
]
}
}
data_1 = {
key_1: {
key_2: [
{
key_2_1: SR_path,
key_2_2: "enable",
key_2_3: [
]
}
]
}
}
for i in range(len(label_list)):
str_add = {'idx': i + 1, 'next-label': label_list[i]}
data_1[key_1][key_2][0]['index'].append(str_add)
with open('data.json', 'w') as outfile:
return json.dump(data_1, outfile, indent=4)
三、HTTPS 放置
因为我想使用HTTPS 请求并使用PUT,所以我实现了该功能make_json(label_list, SR_path)
以便将label_list_SR1
and推label_list_SR2
送到我的路由器中。
def put_explicit_path(self):
filepath = 'data.json'
with open(filepath) as fh:
mydata = fh.read()
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
https_request_index = 'https://' + self.host + '/restconf/data/Cisco-IOS-XE-native:native/ip/explicit-path'
headers = {'Content-type': 'application/yang-data+json', 'Accept': 'application/yang-data+json'}
r = requests.put(https_request_index, data=mydata, auth=(self.user, self.password), headers=headers, verify=False)
if r:
print ("New labels have been pushed")
当我调用该函数make_json(label_list_SR1, label_list_SR1)
时, make_json(label_list_SR1, label_list_SR2)
它会创建如下:
"Cisco-IOS-XE-native:name": [
{
"pname": "SR2",
"mode": "enable",
"index": [
{
"idx": 1,
"next-label": 17011
},
{
"idx": 2,
"next-label": 17012
},
{
"idx": 3,
"next-label": 17013
}
]
}
]
}
从字面上看,它只考虑最后一个函数。我的目标是拥有与我在本节开头的问题中展示的相同的 JSON 文件。我但是,我不明白如何做到这一点。我相信某处功能make_json(label_list, SR_path)
。
解决方案
推荐阅读
- jquery - jquery加载中断html
- python - 从枢轴绘制 Pandas DataFrame
- mysql - 使用未定义的常量 SIGKILL - Laravel 5.7 队列中假定为“SIGKILL”
- excel - 为列中的每个唯一值创建两行并减去
- c# - HTTP 错误 500.30 - ANCM 进程内启动失败
- javascript - 如何动态地将一行添加到 kendo ui 网格(到它的模式)?
- eclipse - 有没有 eclipse cdt api 使用的演示?
- c# - 对象未连接到服务器
- c# - C# 中的 Unity 测验游戏分数
- javascript - 为什么 event.currentTarget null 和 e.target 总是一样的?