[英]python convert string to dictionary json
字符串“輸出”具有以下值:
interface Vlan364
ip policy route-map RM_OUT
interface Vlan234
ip policy route-map RM_OUT
interface Vlan235
ip policy route-map RM_OUT
interface Ethernet1/2
ip policy route-map RM_IN
interface Ethernet1/6
ip policy route-map RM_IN
(1) 如何將其轉換為字典,因此字典“outputDict”如下所示:
{
"interface":"Vlan364", "ip policy route-map":"RM_OUT",
"interface":"Vlan234", "ip policy route-map":"RM_OUT",
"interface":"Vlan235", "ip policy route-map":"RM_OUT",
"interface":"Ethernet1/2", "ip policy route-map":"RM_IN",
"interface":"Ethernet1/6", "ip policy route-map":"RM_IN",
}
這里的目標是識別與每個“接口”相關的“ip policy route-map”。
(2) 如何在上面的字典中找出唯一的“ip policy route-map”並將其放入列表中。 即上述字典中的 output 將是:
route-map_list = [RM_OUT, RM_IN]
您可以使用正則表達式匹配關鍵字,然后使用re.finditer
搜索所有匹配項,並將匹配對象放入字典列表中。
import re, json
output = """interface Vlan364
ip policy route-map RM_OUT
interface Vlan234
ip policy route-map RM_OUT
interface Vlan235
ip policy route-map RM_OUT
interface Ethernet1/2
ip policy route-map RM_IN
interface Ethernet1/6
ip policy route-map RM_IN"""
output_list = []
route_map_list = []
REGEX_STRING = r"interface ([A-Za-z0-9//]+)[\n\r ]+ip policy route-map ([A-Z_]+)"
for match in re.finditer(REGEX_STRING,output):
output_list.append(
{
"interface": match.group(1),
"ip policy route-map": match.group(2)
}
)
if match.group(2) not in route_map_list:
route_map_list.append(match.group(2))
print(json.dumps(output_list, indent=4))
print(route_map_list)
Output:
[
{
"interface": "Vlan364",
"ip policy route-map": "RM_OUT"
},
{
"interface": "Vlan234",
"ip policy route-map": "RM_OUT"
},
{
"interface": "Vlan235",
"ip policy route-map": "RM_OUT"
},
{
"interface": "Ethernet1/2",
"ip policy route-map": "RM_IN"
},
{
"interface": "Ethernet1/6",
"ip policy route-map": "RM_IN"
}
]
['RM_OUT', 'RM_IN']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.