-2

I have the code below.

import json
name = " "
username = " "
ip_address = " "
with open('data6.json', 'r') as myfile:
    data = json.load(myfile)
    for i in data:
        print(i[0].get('Manufacturer'))
        print(i[0].get('Name'))
        print(i[0].get('IPAddress'))

The output is the code like that:

VMware, Inc.
DC01
None
None
None
['192.168.1.240,fe80::350e:d28d:14a5:5cbb']
None
DC01
None

But i want an output like:

VMware, Inc.
DC01
['192.168.1.240,fe80::350e:d28d:14a5:5cbb']

How can i organize my code according to output that i want?

data6.json is like in the below:

[[{"Manufacturer": "VMware, Inc.", "Model": "VMware7,1", "Name": "DC01"}], [{"Index": "1", "IPAddress": ["192.168.1.240,fe80::350e:d28d:14a5:5cbb"]}], [{"Name": "DC01", "UserName": null}]]
ayayay
  • 1
  • 1
  • 5

1 Answers1

0

If you load your initial json File you have: one list -> contains 3 one-element lists -> contains the dict

If you have more of these nestes Lists in files, I would recommend to flatten them If you want your data you have to access the correct one-element list, first index, then get the element in the one-element list, then choose the right value from the dict. Additionally you should close your file handler to close all resources before further working.

with open('data6.json', 'r') as myfile:
    data = json.load(myfile)

print(data[0][0]['Manufacturer'])
print(data[0][0]['Name'])
print(data[1][0]['IPAddress'])
stuckonhere
  • 100
  • 8
  • 1
    Thank you. ['192.168.1.240,fe80::350e:d28d:14a5:5cbb'] for seperating ip and mac addresses i tried split function but it says Attribute Error: 'list' object has no attribute 'split' – ayayay Mar 11 '22 at 09:25
  • That is the same problem as described above. You should read about some basics of Data Types in python it will save you a lot of trouble. The IP-Adress is a one-element list again, that means you have to first access the first element so ```python data[1][0]['IPAddress'][0] ``` and then you have a String, which you can perform functions on. – stuckonhere Mar 11 '22 at 09:49