I want to create a json file via input in my python script that looks like the below code. What is the best way to accomplish this?
File needed
[{
"device_type": "cisco_ios",
"ip": "192.168.1.1"
},
{
"device_type": "cisco_ios",
"ip": "192.168.1.2"
},
{
"device_type": "cisco_ios",
"ip": "192.168.1.3"
}]
I have a loop I created that works for list but I can't get it to work for the format above.
def dev_list():
devices = []
i = 0
while 1:
i += 1
device = input("Enter IP of Device %d: " % i)
if device == "":
break
devices.append(device)
print(devices, "\n")
retry = input("Is your list correct? (y/n) ").strip().lower()
if retry == "no" or retry == "n":
dev_list()
if retry == "yes" or retry == "y":
print("\nScript will continue")
return devices
Python has a built-in package called json, which can be use to work with JSON data. If you have a JSON string, you can parse it by using the json.loads()
method. If you have a Python object, you can convert it into a JSON string by using the json.dumps()
method.
Example:
import json
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
import json
data = {}
data['product'] = []
data['product'].append({
'device_type': 'cisco_ios',
'ip': '192.168.1.1'
})
data['product'].append({
'device_type': 'cisco_ios',
'ip': '192.168.1.2'
})
data['product'].append({
'device_type': 'cisco_ios',
'ip': '192.168.1.3'
})
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)
Assuming you have devices already.
You can dump it to a file with a simple:
import json
with open("resultfile.json", "w") as f:
json.dump(devices, f)
Using with syntax automatically closes the file after the block closes.
https://docs.python.org/3/library/json.html
So it will dump your python object to the file opened.
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.