简体   繁体   English

无法使用python从json提取数据

[英]Unable to pull data from json using python

I have the following json 我有以下JSON

{
    "response": {
        "message": null,
        "exception": null,
        "context": [
            {
                "headers": null,
                "name": "aname",
                "children": [
                    {
                        "type": "cluster-connectivity",
                        "name": "cluster-connectivity"
                    },
                    {
                        "type": "consistency-groups",
                        "name": "consistency-groups"
                    },
                    {
                        "type": "devices",
                        "name": "devices"
                    },
                    {
                        "type": "exports",
                        "name": "exports"
                    },
                    {
                        "type": "storage-elements",
                        "name": "storage-elements"
                    },
                    {
                        "type": "system-volumes",
                        "name": "system-volumes"
                    },
                    {
                        "type": "uninterruptible-power-supplies",
                        "name": "uninterruptible-power-supplies"
                    },
                    {
                        "type": "virtual-volumes",
                        "name": "virtual-volumes"
                    }
                ],
                "parent": "/clusters",
                "attributes": [
                    {
                        "value": "true",
                        "name": "allow-auto-join"
                    },
                    {
                        "value": "0",
                        "name": "auto-expel-count"
                    },
                    {
                        "value": "0",
                        "name": "auto-expel-period"
                    },
                    {
                        "value": "0",
                        "name": "auto-join-delay"
                    },
                    {
                        "value": "1",
                        "name": "cluster-id"
                    },
                    {
                        "value": "true",
                        "name": "connected"
                    },
                    {
                        "value": "synchronous",
                        "name": "default-cache-mode"
                    },
                    {
                        "value": "true",
                        "name": "default-caw-template"
                    },
                    {
                        "value": "blah",
                        "name": "default-director"
                    },
                    {
                        "value": [
                            "blah",
                            "blah"
                        ],
                        "name": "director-names"
                    },
                    {
                        "value": [

                        ],
                        "name": "health-indications"
                    },
                    {
                        "value": "ok",
                        "name": "health-state"
                    },
                    {
                        "value": "1",
                        "name": "island-id"
                    },
                    {
                        "value": "blah",
                        "name": "name"
                    },
                    {
                        "value": "ok",
                        "name": "operational-status"
                    },
                    {
                        "value": [

                        ],
                        "name": "transition-indications"
                    },
                    {
                        "value": [

                        ],
                        "name": "transition-progress"
                    }
                ],
                "type": "cluster"
            }
        ],
        "custom-data": null
    }
}

which im trying to parse using the json module in python. 我正在尝试使用python中的json模块进行解析。 I am only intrested in getting the following information out of it. 我只是想从中获取以下信息。

Name Value operational-status Value health-state Value 名称值操作状态值健康状态值

Here is what i have tried. 这是我尝试过的。 in the below script data is the json returned from a webpage 以下脚本数据中是从网页返回的json

json = json.loads(data)
healthstate= json['response']['context']['operational-status']
operationalstatus = json['response']['context']['health-status']

Unfortunately i think i must be missing something as the above results in an error that indexes must be integers not string. 不幸的是,我认为我一定会缺少一些东西,因为上面的结果导致索引必须是整数而不是字符串的错误。

if I try 如果我尝试

healthstate= json['response'][0]

it errors saying index 0 is out of range. 它错误地指出索引0超出范围。

Any help would be gratefully received. 任何帮助将不胜感激。

json['response']['context'] is a list, so that object requires you to use integer indices. json['response']['context']是一个列表,因此对象要求您使用整数索引。

Each item in that list is itself a dictionary again. 该列表中的每个项目本身又是一本字典。 In this case there is only one such item. 在这种情况下,只有一个这样的项目。

To get all "name": "health-state" dictionaries out of that structure you'd need to do a little more processing: 要使所有"name": "health-state"字典脱离该结构,您需要进行更多处理:

[attr['value'] for attr in json['response']['context'][0]['attributes'] if attr['name'] ==  'health-state']

would give you a list of of matching values for health-state in the first context. 会为您提供第一个上下文中health-state的匹配值列表。

Demo: 演示:

>>> [attr['value'] for attr in json['response']['context'][0]['attributes'] if attr['name'] ==  'health-state']
[u'ok']

You have to follow the data structure. 您必须遵循数据结构。 It's best to interactively manipulate the data and check what every item is. 最好以交互方式处理数据并检查每个项目是什么。 If it's a list you'll have to index it positionally or iterate through it and check the values. 如果是列表,则必须对其进行索引或遍历它并检查值。 If it's a dict you'll have to index it by it's keys. 如果是字典,则必须通过键对其进行索引。 For example here is a function that get's the context and then iterates through it's attributes checking for a particular name. 例如,这里的一个函数获取上下文,然后遍历其属性以检查特定名称。

def get_attribute(data, attribute):
    for attrib in data['response']['context'][0]['attributes']:
        if attrib['name'] == attribute:
            return attrib['value']
    return 'Not Found'

>>> data = json.loads(s)
>>> get_attribute(data, 'operational-status')
u'ok'
>>> get_attribute(data, 'health-state')
u'ok'

json['reponse']['context'] is a list , not a dict . json['reponse']['context']是一个list ,而不是dict The structure is not exactly what you think it is. 结构并不完全是您所想的。

For example, the only "operational status" I see in there can be read with the following: 例如,我在其中看到的唯一“运行状态”可以与以下内容一起阅读:

json['response']['context'][0]['attributes'][0]['operational-status']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM