Getting a KeyError when parsing JSON file

Will91099 :

I just started working with JSON files yesterday, and I've searched other questions relating to KeyError, but none of the answers have helped so far. I'm trying to parse this JSON file and create a dictionary making 'article' the key and 'views' the value. However, I just get a KeyError when trying to print it. The code works if I use a different URL, but I need to use this one. Am I just printing this wrong?

def display(url, text):
    print(url)
    dictionary = json.loads(text)
    for item in dictionary['items']:
        print(f"{item['article']}:\t\t{item['views']}")


def main():
    url = "https://wikimedia.org/api/rest_v1/metrics/pageviews/top/en.wikiversity/all-access/2018/01/all-days"
    display(url, text)



main()
bnlucas :

Looking at the actual JSON data:

{
  "items": [
    {
      "project": "en.wikiversity",
      "access": "all-access",
      "year": "2018",
      "month": "01",
      "day": "all-days",
      "articles": [
        {
          "article": "Psycholinguistics/Models_of_Speech_Production",
          "views": 585462,
          "rank": 1
        },
        {
          "article": "Wikiversity:Main_Page",
          "views": 118971,
          "rank": 2
        },
        {
          "article": "Special:Search",
          "views": 60332,
          "rank": 3
        },

You're not looking for items[n]['article|views'], you're actually looking for items[n]['articles'][n]['article|views']

def display(url, text):
    print(url)
    dictionary = json.loads(text)
    for item in dictionary['items']:
        for article in item['articles']:
            print(f"{article['article']}:\t\t{article['views']}")

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=386148&siteId=1