简体   繁体   中英

Adding json data file to another common json file in Python

First of all I have search the similar issues of mine but none able to answer my question above. I hope you guys could advise me further.

I' running a script to extract data from a list of network equipment and save the value onto json file for example below

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

Then a line of code is used to get data of devicename,ipaddress and lldp, return the value, extract it and save it onto the data list above. For example

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

For my[data[2]], lldp neighbors will return data in xml format and convert that xml data onto json format file like below

LLDP NEIGHBORS DETAILS:-

"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"
}

My questions here is how can i add lldp neighbors detail above (json data) onto temp[data[2]] of json-1 so that the final json file json.dump(json-1, fp) generated will be like below, nested json file

{
  "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"
      }
    ]
  ]
}

I really hope someone could point me to the right path...i'm stuck ...please assist me. Thank you.

Your data should be a dictionary type, now a tuple type


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') 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM