Home > Software design >  Parsing API Json (dictionary) response using python
Parsing API Json (dictionary) response using python

Time:11-14

I'm trying to parse a nested dictionary looking json response from a API URL. I'm trying to get the 'id' and 'symbol' and put it in to a list so that I can merge it with another list later.

I have tried:

try:
response = session.get(url, params=parameters)
data = json.loads(response.text)
for x in data:
print(data['data'][0]['id'])

But it just returns "1" two times so i'm guessing the loop is not within the dictionary

print(type(data))
<class 'dict'>

I would need a loop to get every iteration of 'id' and 'symbol' and append it to a list.

   {
  "status": {
    "timestamp": "2021-11-13T20:50:29.375Z",
    "error_code": 0,
    "error_message": null,
    "elapsed": 11,
    "credit_count": 1,
    "notice": null
  },
  "data": [
    {
      "id": 1,
      "name": "Bitcoin",
      "symbol": "BTC",
      "slug": "bitcoin",
      "rank": 1,
      "is_active": 1,
      "first_historical_data": "2013-04-28T18:47:21.000Z",
      "last_historical_data": "2021-11-13T20:39:02.000Z",
      "platform": null
    },
    {
      "id": 2,
      "name": "Litecoin",
      "symbol": "LTC",
      "slug": "litecoin",
      "rank": 14,
      "is_active": 1,
      "first_historical_data": "2013-04-28T18:47:22.000Z",
      "last_historical_data": "2021-11-13T20:39:02.000Z",
      "platform": null
    },
    {
      "id": 3,
      "name": "Namecoin",
      "symbol": "NMC",
      "slug": "namecoin",
      "rank": 778,
      "is_active": 1,
      "first_historical_data": "2013-04-28T18:47:22.000Z",
      "last_historical_data": "2021-11-13T20:39:02.000Z",
      "platform": null
    },
    {
      "id": 4,
      "name": "Terracoin",
      "symbol": "TRC",
      "slug": "terracoin",
      "rank": 2062,
      "is_active": 1,
      "first_historical_data": "2013-04-28T18:47:22.000Z",
      "last_historical_data": "2021-11-13T20:39:03.000Z",
      "platform": null
    },
    {
      "id": 5,
      "name": "Peercoin",
      "symbol": "PPC",
      "slug": "peercoin",
      "rank": 707,
      "is_active": 1,
      "first_historical_data": "2013-04-28T18:47:23.000Z",
      "last_historical_data": "2021-11-13T20:39:02.000Z",
      "platform": null
    }
  ]
}

Any help is much appreciated.

CodePudding user response:

response = session.get(url, params=parameters)
data = json.loads(response.text)
for x in data:
    print(x['data'][0]['id'])

Another way:

response = session.get(url, params=parameters)
data = json.loads(response.text)
for x in data["data"]:
    print(x['id'])

Just beautiful way:

response = session.get(url, params=parameters).json()
for x in response:
    print(x['data'][0]['id'])

Beautiful way if you need to use response data in other way:

response = session.get(url, params=parameters)
for x in response.json():
    print(x['data'][0]['id'])
  • Related