使用python操作JSON

时间:2017-04-20 19:39:54

标签: python json ansible

我试图操纵JSON数据以匹配Ansible的特定格式。我是python和编程的新手。我似乎无法弄清楚如何做到这一点。这是我的相关代码:

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=('dmitry', 'security'))

jsonget = req.json()


def get_list(self):
        hostsData = jsonget
        print "Test json before manipulation:\n"
        print(hostsData)
        print "\n\n"
        for item in hostsData['results']:
            print '' + item['Vendor']
            for item in hostsData['results']:
                print 'hosts:' + item['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'}]}



    Cisco
hosts:10.150.190.2
hosts:10.150.250.3
hosts:10.255.255.42
hosts:10.58.1.1
hosts:10.33.93.1
hosts:10.33.93.2
hosts:10.33.93.3
hosts:10.33.93.4
hosts:10.33.93.6
hosts:10.33.93.7
Cisco
hosts:10.150.190.2
hosts:10.150.250.3
hosts:10.255.255.42
hosts:10.58.1.1
hosts:10.33.93.1
hosts:10.33.93.2
hosts:10.33.93.3
hosts:10.33.93.4
hosts:10.33.93.6
hosts:10.33.93.7
Unknown
...

我想要做的是输出类似Ansible可以阅读的内容:

{
    "Cisco"   : {
        "hosts"   : [ "10.150.190.2", "10.150.250.3" ],
            },
    "Unknown"  : 
        "hosts"   : [ "10.255.255.42" ],
},

感谢您的帮助。

CB

1 个答案:

答案 0 :(得分:0)

编辑:

import pprint
import simplejson

# Your long string
s = {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'}]}



# Eval the Json to python friendly dict
dumped = eval(simplejson.dumps(s))

# Make a set of vendors (no duplicates)
vendor_set = set()
for value in dumped['results']:
    vendor_set.add(value['Vendor'])

# Make a new dict based on these vendors
final_dict = dict.fromkeys(vendor_set)

# Loop over the dict, conditionally adding IPAddresses to the hosts key for each vendor
for key in final_dict:
    for v in dumped['results']:
        if final_dict[key] is not None:
            if key in str(v):
                final_dict[key]['hosts'].append(v['IPAddress'])
        else:
            final_dict[key] = {'hosts': []}

# Print it (somewhat) nicely
pprint.pprint(final_dict)

# Prints:
{'Cisco': {'hosts': ['10.150.250.3',
                     '10.33.93.1',
                     '10.33.93.2',
                     '10.33.93.4',
                     '10.33.93.7']},
 'Juniper Networks/NetScreen': {'hosts': ['10.58.1.1']},
 'Unknown': {'hosts': ['10.255.255.42', '10.33.93.3', '10.33.93.6']}}