[英]Read piped input from other script, while also reading user input, in Python (2.7 and 3.x)
[英]Creating a json file from user input in python 3.X
我想通过在我的python脚本中输入以下内容来创建一个json文件,如下所示。 做到这一点的最佳方法是什么?
需要档案
[{
"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"
}]
我创建了一个适用于列表的循环,但无法使其适用于上述格式。
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有一个称为json的内置程序包,可用于处理JSON数据。 如果您有JSON字符串,则可以使用json.loads()
方法进行解析。 如果您有Python对象,则可以使用json.dumps()
方法将其转换为JSON字符串。
例:
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)
假设您已经有设备 。
您可以使用以下简单的方法将其转储到文件中:
import json
with open("resultfile.json", "w") as f:
json.dump(devices, f)
在块关闭后,使用with语法会自动关闭文件。
https://docs.python.org/3/library/json.html
因此它将把您的python对象转储到打开的文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.