我正在使用 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
或者类似的东西。
希望您能理解我想做什么。
答案 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
>>>