![](/img/trans.png)
[英]Python for loop json.loads error string indices must be integers
[英]Getting error as string indices must be integers while using for loop in python
我有一個字典列表:
出去:
[
{
"dest_host": "AA",
"sysname": "",
"mgmt_ip": "1.1.1.1",
"platform": "switch",
"remote_port": "E1/48",
"local_port": "G0/2",
"version": "",
"interface_ip": ""
},
{
"dest_host": "BB",
"sysname": "",
"mgmt_ip": "1.1.1.2",
"platform": "switch",
"remote_port": "E1/40",
"local_port": "G0/1",
"version": "",
"interface_ip": ""
}]
這是我的 for 循環:
for i in out:
print('port:'+i['local_port'],'--->','nei_host:'+i['dest_host'],'--->','nei_port:'+i['remote_port'])
錯誤 -
print('port:'+i['local_port'],'--->','nei_host:'+i['dest_host'],'--->','nei_port:'+i['remote_port'])
TypeError: string indices must be integers
我想打印什么:
port:G0/2 --> nei_host:AA ---> nei_port:E1/48
port:G0/1 --> nei_host:BB ---> nei_port:E1/40
有人可以幫我找出 for 循環中的錯誤嗎? 我是 python 的新手。 謝謝
cdpnei = ssh.send_command('show cdp neigh detail', use_textfsm=True)
out = json.dumps(cdpnei, indent = 4)
我假設 out 是 dict,所以我針對out
運行 for 循環
正如@TimRoberts 建議的那樣,我針對實際字典中的cdpnei
運行 for 循環
for i in cdpnei:
print('port:'+i['local_port'],'--->','nei_host:'+i['dest_host'],'--->','nei_port:'+i['remote_port'])
這起到了作用,按預期工作。
port:G0/2 --> nei_host:AA ---> nei_port:E1/48
port:G0/1 --> nei_host:BB ---> nei_port:E1/40
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.