将json数据文件添加到Python中的另一个常见json文件

时间:2019-02-21 09:00:10

标签: python json junos-automation

首先,我搜索了与我类似的问题,但没有一个能够回答我上面的问题。我希望你们能进一步建议我。

我正在运行一个脚本,以从网络设备列表中提取数据并将其值保存到json文件中,例如下面的

json-1 = {
  "channel": "scanner",
  "action": "create_device",
  "table": "U2",
  "device":[]
}
data = "device_name","ip_address","lldp_neighbors"

然后使用一行代码来获取设备名称,ipaddress和lldp的数据,返回该值,将其提取并保存到上面的数据列表中。例如

my[data[0]] = connection.find_prompt().rstrip('>') #to get hostname
my[data[1]] = device['ip'] #to get ip address
my[data[2]] = connection.send_command('show lldp neighbors | display xml') 
#to get lldp data in xml format

json1["device"].append(my) #append my data to device

对于my [data [2]],lldp邻居将以xml格式返回数据并将该xml数据转换为json格式文件,如下所示

LLDP邻居详细信息:-

"lldp_neighbors": [
{
"local-port": "xe-3/0/4.0",
"parent-interface": "ae31.0",
"chassis-id": "b0:c6:9a:63:80:40",
"port-info": "xe-0/0/0/0.0",
"system-name": "host.jnpr.net"
}

我的问题是如何将上面的lldp邻居详细信息(json数据)添加到json-1的temp [data [2]]上,以便生成的最终json文件json.dump(json-1,fp)如下所示,嵌套的json文件

{
  "channel": "scanner",
  "action": "create_device",
  "table": "U2",
  "device": [
    {
      "device_name": "rtr1.wer",
      "ip_address": "1.1.1.1",
      "lldp_neighbors": [
      {
       "local-port": "xe-3/0/4.0",
       "parent-interface": "ae31.0",
       "chassis-id": "b0:c6:9a:63:80:40",
       "port-info": "xe-0/0/0/0.0",
       "system-name": "host.jnpr.net"
      }
    ]
  ]
}

我真的希望有人能指出我正确的道路...我被困住了...请协助我。谢谢。

1 个答案:

答案 0 :(得分:0)

您的data应该是字典类型,现在是元组类型


data = "device_name","ip_address","lldp_neighbors"
# change to
data = {"device_name": "","ip_address": "","lldp_neighbors": []}
my[data["device_name"]] = connection.find_prompt().rstrip('>') #to get hostname
my[data["ip_address"]] = device['ip'] #to get ip address
my[data["lldp_neighbors"]] = connection.send_command('show lldp neighbors | display xml')