简体   繁体   中英

Getting a KeyError when parsing JSON file

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()

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']}")

The is only one thing wrong with your code:

There is no article key on items you are iteration. Actually, there is a list of articles in it. So, if you just add:

for article in item['articles']:

It will work (change your display method):

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']}")

Use a json viewer like in firefox to browse the json. You're not referencing it correctly.

First, that page only has one entry in items, so iterating seems weird.

Either way, in your for loop, each item is a dict. There is key called articles that is a list of dicts, so you'll need a nested loop.

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']}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM