0

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'])
5
  • 4
    OK, so there isn't a 'records' key in the json_obj dictionary. Beyond that, what do you think anyone can tell you? Do you know what keys it does have? Have you tried printing them out? Doing any other debugging? Commented Feb 27, 2017 at 22:34
  • As jonrsharpe said, take a look at what keys there actually are: console.log(Object.keys(json_obj)) should make it easy to see. Commented Feb 27, 2017 at 22:41
  • 1
    Peeking at the data, you want json_obj["result"]["records"] Commented Feb 27, 2017 at 22:43
  • 1
    @RichardDunn right idea, wrong language! Commented Feb 28, 2017 at 7:59
  • 1
    @jonrsharpe oh dear. That's what working in both all day and then staying up late gets me. print(json_obj.keys()) in that case... Or better still, what I use to explore data in python: from pprint import pprint then simply pprint(json_obj) Commented Feb 28, 2017 at 11:27

1 Answer 1

1

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'])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Serge. This solved the problem. I didn't know that I have to use ["result"]["records"] instead of just ["records"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.