转换具有多个字典外观的字符串

时间:2019-06-26 10:57:20

标签: python python-3.x

说明

我正在使用 psycopg2 来存储我的结果并进行恢复。我将这样的列表存储在表中:

[{"vlan": "715", "intf": "0/3", "intf2": "0/4"}, {"vlan": "", "intf": "0/5", "intf2": "0/6"}, {"vlan": "", "intf": "0/7", "intf2": ""}]

当我对此表执行SELECT时,输出如下:

[('[{"vlan": "715", "intf": "0/3", "intf2": "0/4"}, {"vlan": "", "intf": "0/5", "intf2": "0/6"}, {"vlan": "", "intf": "0/7", "intf2": ""}]',)]

要打印字符串,我要做:

test = [('[{"vlan": "715", "intf": "0/3", "intf2": "0/4"}, {"vlan": "", "intf": "0/5", "intf2": "0/6"}, {"vlan": "", "intf": "0/7", "intf2": ""}]',)]

print(type(test))
test = test[0][0]
print(type(test))

out:
<class 'list'>
<class 'str'>

我尝试过的

我尝试使用模块 json ast ,但由于我认为有多种用法,我没有成功。

我想做什么

我想浏览字典(当前是一个字符串),并得到这样的结果:

for om in test
    print(om["intf"])

out:
0/3
0/5
0/7

或者类似的东西。

希望您能理解我想做什么。

2 个答案:

答案 0 :(得分:4)

您有一个嵌入在JSON字符串中的字典列表。

使用此代码提取数据:

import json

test = [('[{"vlan": "715", "intf": "0/3", "intf2": "0/4"}, {"vlan": "", "intf": "0/5", "intf2": "0/6"}, {"vlan": "", "intf": "0/7", "intf2": ""}]',)]
j = json.loads(test[0][0]) #list of dicts

for d in j:
    print(d['intf'])

输出:

0/3
0/5
0/7

答案 1 :(得分:2)

json.loads会更好:

import json
lot = json.loads(lot[0][0])
for i in lot:
    print(i['intf'])

输出:

0/3
0/5
0/7
>>>