簡體   English   中英

根據python 3.X中的用戶輸入創建json文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM