I’m a network engineer who is learning python. Recently I’ve been working with json files, reading data via python, but am struggling to figure out the method to convert IP address strings into a list and ping each. I thought that taking this approach would be a good way to see how python works in a networking enviroment.
The json file contents are:
[
{
"name": "Router02",
"host": "10.1.2.13"
}
{
"name": "Router03",
"host": "10.0.1.13"
}
]
import json
from pythonping import ping
with open ('credentials.json', 'r') as f:
hosts = json.load(f)
for router in hosts:
print(router['host'])
Host = (router['host'])
ping(Host, verbose=True)
With this code I can ping the first address, as I understand that this takes the json data and converts into a dictionary, which cannot have duplicate key values. Converting to a list of IP addresses is the way forward.
How do I open the json file and convert the contents of the file to a list? Ideally I want to list only the IP addresses.
I’ve been trying variations, cut code right back to this to see if the file open and converison to a list has been successful:
import json
from pythonping import ping
with open ('credentials.json', 'r') as f:
hosts = json.loads('credentials.json')
print (hosts)
Have tried subsituting loads with dumps to but keep getting traceback errors.
I expected the print output to show me the list contents.
2
Answers
Thanks for the feedback. I used notepad++ with the json viewer to sort out the file format,which resolved that issue.
To answer @jarmod the file name was odd as it started life as a credentials file but ended up being a list of hosts as I found my way around.
Also, to answer @DarkKnight, I'm running this on windows which doesn't care about who runs as what! I did have that issue with ping when running python scripts on Ubuntu earlier though.
(list entries should be separated by comma)
Your final code could look like this (assuming that your JSON is correct):