-3

I am calling an API which returns a complicated json:

{"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"
             }]}

How do I extract just the name and state for attrs?

Anwarvic
  • 12,156
  • 4
  • 49
  • 69
dom
  • 9

3 Answers3

0

Use the json module:

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

Note that I had to add a missing " near the end of your string - I hope it only disappeared when you copied it here.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
0

As @Aran-Fey suggested, you should use the json module, which turns the JSON string into Python dicts and lists.

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'])

Btw, there's a syntax error in your JSON example. A double quote is missing before the first occurrence of 'Host'.

r0the
  • 617
  • 4
  • 13
0

Pretty much the same answer as Thierry. Same issue with the json being invalid.

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))
Keith John Hutchison
  • 4,955
  • 11
  • 46
  • 64