Python JSON键错误,但关键匹配

时间:2017-04-20 15:38:36

标签: python ansible

新手程序员试图从Solarwinds获得动态库存到Ansible。我通过休息连接到Solarwinds并获得我需要的数据。当我运行脚本时,我收到一个关键错误。我不明白为什么当我看到钥匙表明它是错误的时候。

以下是代码:

import os
import sys
import argparse
import ConfigParser

try:
    import json
except ImportError:
    import simplejson as json

import requests

payload = 'query=SELECT+TOP+10+IPAddress,+Vendor+FROM+Orion.Nodes'
url = "https://10.150.199.44:17778/SolarWinds/InformationService/v3/Json/Query"
req = requests.get(url, params=payload, verify=False, auth=('ansible', 'pass'))

jsonget = req.json()

    def get_list(self):
        hostsData = jsonget
        print "Test json before manipulation:\n"
        print(hostsData)
        print "\n\n"
        if hostsData['Vendor'] == []:
            print ''
        else:
            for rows in hostsData['Vendor']:
                print 'hosts:' + rows['IPAddress']

这是我的输出:

./swinds.py --list
Test json before manipulation:

{u'results': [{u'Vendor': u'Cisco', u'IPAddress': u'10.150.190.2'}, {u'Vendor': u'Cisco', u'IPAddress': u'10.150.250.3'}, {u'Vendor': u'Unknown', u'IPAddress': u'10.255.255.42'}, {u'Vendor': u'Juniper Networks/NetScreen', u'IPAddress': u'10.58.1.1'}, {u'Vendor': u'Cisco', u'IPAddress': u'10.33.93.1'}, {u'Vendor': u'Cisco', u'IPAddress': u'10.33.93.2'}, {u'Vendor': u'Unknown', u'IPAddress': u'10.33.93.3'}, {u'Vendor': u'Cisco', u'IPAddress': u'10.33.93.4'}, {u'Vendor': u'Unknown', u'IPAddress': u'10.33.93.6'}, {u'Vendor': u'Cisco', u'IPAddress': u'10.33.93.7'}]}



Traceback (most recent call last):
  File "./swinds.py", line 75, in <module>
    SwInventory()
  File "./swinds.py", line 41, in __init__
    self.inventory = self.get_list()
  File "./swinds.py", line 57, in get_list
    if hostsData['Vendor'] == []:
KeyError: 'Vendor'
test@ubuntu:/etc/ansible$

为什么我收到此错误?谢谢你的帮助。

CB

1 个答案:

答案 0 :(得分:0)

你没有JSON对象,你有一个从JSON创建的python字典。我不知道你是如何达到你在你的例子中所展示的那样的,但是JSON很容易在python列表/ dicts和实际的JSON之间互换。我怎么知道它不是JSON?您在字符串和单引号前面有unicode u,例如'代替"。最后,当你在Python本地工作时,你可以以同样的方式使用它们,但你应该意识到这种区别。

您有一个包含一个密钥的字典:results。它映射到列表作为值(您可以索引),该列表中的每个项目都是字典本身。如果您想打印hosts:和IP地址(如评论中所示):

hostsData = {u'results': [{u'Vendor': u'Cisco', u'IPAddress': u'10.150.190.2'}, {u'Vendor': u'Cisco', u'IPAddress': u'10.150.250.3'}, {u'Vendor': u'Unknown', u'IPAddress': u'10.255.255.42'}, {u'Vendor': u'Juniper Networks/NetScreen', u'IPAddress': u'10.58.1.1'}, {u'Vendor': u'Cisco', u'IPAddress': u'10.33.93.1'}, {u'Vendor': u'Cisco', u'IPAddress': u'10.33.93.2'}, {u'Vendor': u'Unknown', u'IPAddress': u'10.33.93.3'}, {u'Vendor': u'Cisco', u'IPAddress': u'10.33.93.4'}, {u'Vendor': u'Unknown', u'IPAddress': u'10.33.93.6'}, {u'Vendor': u'Cisco', u'IPAddress': u'10.33.93.7'}]}

for item in hostsData['results']:
    print "Hosts: " + item['IPAddress']