0

I am trying to load in a JSON file via an API which returns the following:

{
    "success": true,
    "message": "",
    "data": {
        "account_sid": "ABCDEFGHIJK",
        "sites": [
            {
                "name": "1",
                "devices": [
                    {
                        "serial": "12345678",
                        "name": null,
                        "instruments": [
                            {
                                "serial": "WWW",
                                "name": "DEV1"
                            },
                            {
                                "serial": "XXX",
                                "name": "DEV2"
                            },
                            {
                                "serial": "YYY",
                                "name": "DEV3"
                            },
                            {
                                "serial": "ZZZ",
                                "name": "DEV4"
                            }
                        ]
                    }
                ]
            }
        ]
    }
}

What I am trying to do is access the "instruments" section and store each serial within a dictionary. So: data -> sites -> devices -> instruments.

I am trying to do this by:

response = requests.post(URL)
returned_data = json.loads(response.text.encode().decode('utf-8-sig'))

print(json.dumps(returned_data, indent=4))

devices = dict()
for device in returned_data['data']:
    device_id = device['sites']['devices']['instruments']['serial']
    device_name = device['sites']['devices']['instruments']['name']
    devices[device_name] = device_id

However, on each attempt to run, I receive the following error:

Exception has occurred: TypeError
string indices must be integers
  File "C:\Users\me\Documents\file.py", line 55, in <module>
    device_id = device['sites']['devices']['instruments']['serial']

I am relatively new to python, so any pointers would be a great help.

jabroni
  • 167
  • 16

1 Answers1

0

I am fairly certain I have figured it out. If you look at how the json is written, it's written like a key pair or a dictionary.

So you can access each subsequent element by looking at opening elements such as:

    "data": {
        "account_sid": "ABCDEFGHIJK",
        "sites": [

Which can be accessed with:

print(json.dumps(y['data']['sites']

and each "pair" after that accessed with its index

                "name": "1",
                "devices": [

as:

print(json.dumps(y['data']['sites'][0]

So if I wanted to access a "name": "2" then that would be: print(json.dumps(y['data']['sites'][1]

So in full, to get to the serial WWW it would be:

print(json.dumps(y['data']['sites'][0]['devices'][0]['instruments'][1],indent=4))         #indent=4 for formatting

This pointed me in the right direction: Accessing JSON elements

jabroni
  • 167
  • 16