如何在python 2.7.5中解析复杂的json?

时间:2015-05-14 17:22:40

标签: python json

我尝试使用Puppet的REST API从Puppet Enterprise 3.7 puppet master中列出我的puppet类的名称。

这是我的剧本:

#!/usr/bin/env python

import requests
import json

url='https://ppt-001.example.com:4433/classifier-api/v1/groups'
headers = {"Content-Type": "application/json"}
data={}
cacert='/etc/puppetlabs/puppet/ssl/certs/ca.pem'
key='/etc/puppetlabs/puppet/ssl/private_keys/ppt-001.example.com.pem'
cert='/etc/puppetlabs/puppet/ssl/certs/ppt-001.example.com.pem'
result = requests.get(url,
        data=data, #no data needed for this request
        headers=headers, #dict {"Content-Type":"application/json"}
        cert=(cert,key), #key/cert pair 
        verify=cacert
        )
print json.dumps( result.json(), sort_keys=True, indent=4, separators=(',', ': ')) 
for i in result.json:
    print i

以下是执行脚本时收到的错误消息:

Traceback (most recent call last):
  File "./add-group.py", line 42, in <module>
    for i in result.json:
TypeError: 'instancemethod' object is not iterable

以下是我从REST API返回的数据示例:

[
    {
        "classes": {},
        "environment": "production",
        "environment_trumps": false,
        "id": "00000000-0000-4000-8000-000000000000",
        "name": "default",
        "parent": "00000000-0000-4000-8000-000000000000",
        "rule": [
            "and",
            [
                "~",
                "name",
                ".*"
            ]
        ],
        "variables": {}
    },
    {
        "classes": {
            "puppet_enterprise": {
                "certificate_authority_host": "ppt-001.example.com",
                "console_host": "ppt-001.example.com",
                "console_port": "443",
                "database_host": "ppt-001.example.com",
                "database_port": "5432",
                "database_ssl": true,
                "mcollective_middleware_hosts": [
                    "ppt-001.example.com"
                ],
                "puppet_master_host": "ppt-001.example.com",
                "puppetdb_database_name": "pe-puppetdb",
                "puppetdb_database_user": "pe-puppetdb",
                "puppetdb_host": "ppt-001.example.com",
                "puppetdb_port": "8081"
            }
        },
        "environment": "production",
        "environment_trumps": false,
        "id": "52c479fe-3278-4197-91ea-9127ba12474e",
        "name": "PE Infrastructure",
        "parent": "00000000-0000-4000-8000-000000000000",
        "variables": {}
    },
.
.
.

我应该如何访问name密钥并获取defaultPE Infrastructure等值?

我已经在SO上阅读了其他答案,说我应该使用json.loads()并尝试使用parsed_json = json.loads(result.json()),但会出现此错误消息:

Traceback (most recent call last):
  File "./add-group.py", line 38, in <module>
    parsed_json = json.loads(result.json())
  File "/usr/lib64/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer

1 个答案:

答案 0 :(得分:1)

print json.dumps( result.json(), sort_keys=True, indent=4, separators=(',', ': ')) json.dumps的第一个参数必须是字符串或缓冲区,如获取的TypeError(TypeError: expected string or buffer)所述。

您的变量结果是Response的实例,方法.json()将返回字典。由于您将.json()的结果传递给json.dumps(),因此您收到错误消息。您可以使用result.json()已经是与您的响应相对应的字典,或者将您的json.dumps行更改为print json.dumps( result.text, sort_keys=True, indent=4, separators=(',', ': ')),其中result.text是您的JSON结果字符串/ unicode。< / p>

更改后,要访问类似name属性的内容,您可以执行以下操作:

for item in r.json():
    try:
        print item['name']
    expect KeyError:
        print "There is no 'name' attribute"