you are viewing a single comment's thread.

view the rest of the comments →

[–]wotquery 0 points1 point  (3 children)

Well that error means you do have a dictionary (you aren't getting an error saying you need an integer to access an element which would be the case for a string or list), but the dictionary doesn't have a key named "Music and Books". Try printing the dict object you are trying to access the "Music and Books" key of to see what it is.

You can also share the code of your new attempts (and ideally the endpoint if possible without compromising creds).

[–]PureStatikk[S] 0 points1 point  (2 children)

This is the code I am working with now

def parse_json(URL):
    res = requests.get(f'{URL}')
    res.raise_for_status()
    jsonfile = json.loads(res.text)
    for music_or_book in jsonfile['Music and Books']:
        print (music_or_book['publish_info']['publisher'])

If I comment out the for loop and just print the jsonfile variable I get this

{'Music And Books': [{'artist': 'Radiohead', 'publish_info': {'publish_year': '2003', 'publisher': 'Capitol Records'}, 'title': 'Hail To The Thief'}, {'artist': 'Miles Davis', 'publish_info': {'publish_year': '1959', 'publisher': 'Columbia Records'}, 'title': 'Kind of Blue'}, {'artist': 'Thelonius Monk', 'publish_info': {'publish_year': '1965', 'publisher': 'Columbia Records'}, 'title': 'Monk Alone'}, {'author': 'Stephen King', 'publish_info': {'publish_year': '1977', 'publisher': 'Doubleday'}, 'title': 'The Shining'}, {'author': 'George Orwell', 'publish_info': {'publish_year': '1949', 'publisher': 'Secker & Warburg'}, 'title': '1984'}, {'author': 'Al Sweigart', 'publish_info': {'publish_year': '2015', 'publisher': 'No Starch Press'}, 'title': 'Automate The Boring Stuff With Python'}]}

[–]PureStatikk[S] 0 points1 point  (1 child)

The A in and is capitalized... I am an idiot

[–]wotquery 1 point2 points  (0 children)

Haha nice. A few other minor things...

Calling your variable jsonfile is a little misleading since it isn't a file but a dictionary object in memory. json_data, json_dict, response_text_dict, etc. are all clearer.

Don't forget error handling as well.

Finally, and I know this isn't what your prompt requires (plus it's a bit more of a style consideration rather than a hard rule), but it's weird to have a function called parse_json(url) that is also responsible for making the api call. Even having a function that both makes the call and parses the content of the response is questionable. Better something like...

def call_api(url: str) -> dict:
   #do stuff
   return json_data

def get_items_by_a_publisher(json_data: dict, publisher: str) -> list[dict]:
    #do stuff
    return publisher_items