user7632376
user7632376

Reputation: 11

Python Json - KeyError

I am trying to retrieve the records from an API and eventually want to store them in a dataframe so that I can do some analytics. But I am getting the following error:

  for item in json_obj["records"]:
KeyError: 'records'

Code:

import urllib.request
import json

import urllib.request
url = 'https://eservices.mas.gov.sg/api/action/datastore/search.json?resource_id=7f1363cc-3875-4e03-a389-fc47342bb840&limit=5'

response = urllib.request.urlopen(url).read().decode('UTF-8')
json_obj = json.loads(response)

for item in json_obj["records"]:
    print(item[end_of_month'])
    print(item['preliminary'])
    print(item['cards_main'])

Upvotes: 0

Views: 2216

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148900

When you cannot find a key where the API doc says that it should be there, you should just print the text of the json, because it is a text format.

Here, it would be evident that the records key does exist but is not a top level one but a sub-key of result.

Your code should be:

for item in json_obj["result"]["records"]:
    print(item['end_of_month'])
    print(item['preliminary'])
    print(item['cards_main'])

Upvotes: 1

Related Questions