Home > Enterprise >  Getting specific value out of the JSON response
Getting specific value out of the JSON response

Time:02-02

I am trying to get a specific data out of the JSON file and write it to the output file groups.json. Error I am getting is as follows.

Traceback (most recent call last):
  File "C:/Code/ApicaAPIRequests/get_groups.py", line 15, in <module>
    new_data = [{"id": x["id"], "name": x["name"]} for x in data["groups"]]
TypeError: list indices must be integers or slices, not str

Code example without getting nested items:

import requests
import json

url = "***"

response = requests.request("GET", url)

data = response.json()

new_data = [{"id": x["id"], "name": x["name"]} for x in data["groups"]]

with open('groups.json', 'w') as f:
    json.dump(data, f)

print(json.dumps(new_data, indent=2))

The JSON data is as follows. I need to be able to filter out id with name, then groups and id, name under inside the groups.

[
    {
        "id": 13061,
        "name": "***",
        "rank": 9999999,
        "groups": [
            {
                "id": 13062,
                "name": "***",
                "rank": 9999999,
                "groups": null
            }, {
                "id": 13063,
                "name": "***",
                "rank": 9999999,
                "groups": null
            }, {
                "id": 13064,
                "name": "***",
                "rank": 9999999,
                "groups": null
            }
        ]
    },
    {
        "id": 11139,

Would appreciate any advice as I am learning coding and getting my brain melt.

CodePudding user response:

There is no groups key at top level. data is list of dicts. Each dict has id and name, but also groups keys. To access all id and name in groups you need to iterate over x['groups'] and for each dict again extract id and name. List comprehension would not do here. you need regular, nested loops or loop and list comprehension, like this:

data = response.json()
new_data = []

for item in data:
    new_data.append({"id": item["id"], "name": item["name"]}) # remove this, if you want just the groups
    groups = [{"id": gr["id"], "name": gr["name"]} for gr in item["groups"]]
    new_data.extend(groups)

Note, I don't know the data, so it is possible that there are duplicate values in new_data.

If you want just the groups, this will do too

new_data = [{"id": x["id"], "name": x["name"]} for item in data for x in item["groups"]]
  •  Tags:  
  • Related