将Python Json转换为dict

时间:2019-03-10 08:13:51

标签: python

我正在调用一个返回复杂json的API:

{"results": [{"attrs": {"name": "par.abd","state": 1.0},
              "joins": {},
              "meta": {},
              "name": "par.abd",
              "type": Host"
             },
             {"attrs": {"name": "bbc.abd","state": 1.0},
              "joins": {},
              "meta": {},
              "name": "bbc.abd",
              "type": "Host"
             }]}

如何仅提取attrs的名称和状态?

3 个答案:

答案 0 :(得分:0)

使用json模块:

import json

json_string = """{"results": [{"attrs": {"name": "par.abd","state": 1.0},"joins": {},"meta": {},"name": "par.abd","type": "Host"},{"attrs": {"name": "bbc.abd","state": 1.0},"joins": {},"meta": {},"name": "bbc.abd","type": "Host"} ]}"""
data = json.loads(json_string)

for res in data['results']:
    print(res['attrs']['name'], res['attrs']['state'])


# par.abd 1.0
# bbc.abd 1.0

请注意,我必须在字符串结尾处添加一个丢失的"-我希望它仅在您将其复制到此处后消失。

答案 1 :(得分:0)

按照@ Aran-Fey的建议,您应该使用json模块,该模块将JSON字符串转换为Python字典和列表。

import json

json_string = '{"results": [{"attrs": {"name": "par.abd","state": 1.0},"joins": {},"meta": {},"name": "par.abd","type": "Host"},{"attrs": {"name": "bbc.abd","state": 1.0},"joins": {},"meta": {},"name": "bbc.abd","type": "Host"} ]}'
data = json.loads(json_string)
for item in data['results']:
    attrs = item['attrs']
    print(attrs['name'], attrs['state'])

顺便说一句,您的JSON示例中存在语法错误。第一次出现“主机”之前,双引号丢失了。

答案 2 :(得分:0)

答案与Thierry差不多。 json无效也是同样的问题。

import json
text = '''{
    "results": [
        {
            "attrs": {
                "name": "par.abd",
                "state": 1.0
            },
            "joins": {
            },
            "meta": {
            },
            "name": "par.abd",
            "type": "Host"
        },
        {
            "attrs": {
                "name": "bbc.abd",
                "state": 1.0
            },
            "joins": {
            },
            "meta": {
            },
            "name": "bbc.abd",
            "type": "Host"
        }
    ]
}
'''
payload = json.loads(text)
results = payload['results']
for result in results:
    attrs = result['attrs']
    name = attrs['name']
    state = attrs['state']
    print("name: %s state: %s"%(name,state))