Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parse JSON in python problem with syntax with square brackets

I have a JSON received from an API where is A word definition from English Dictionary. I need to parse the data and separate meanings, definitions, and examples but I have some syntax problems with the JSON file.

Here is an example received JSON for the word Handsome:

[{"word":"handsome","phonetic":"/ˈhæn.səm/","phonetics":[{"text":"/ˈhæn.səm/","audio":"https://api.dictionaryapi.dev/media/pronunciations/en/handsome-uk.mp3","sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=9021972","license":{"name":"BY 3.0 US","url":"https://creativecommons.org/licenses/by/3.0/us"}},{"text":"/ˈhæn.səm/","audio":"https://api.dictionaryapi.dev/media/pronunciations/en/handsome-us.mp3","sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=1648256","license":{"name":"BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"}}],"meanings":[{"partOfSpeech":"verb","definitions":[{"definition":"To render handsome.","synonyms":[],"antonyms":[]}],"synonyms":[],"antonyms":[]},{"partOfSpeech":"adjective","definitions":[{"definition":"(of people, things, etc) Having a good appearance; good-looking.","synonyms":[],"antonyms":[],"example":"a handsome garment, house, tree, or horse"},{"definition":"Good, appealing, appropriate.","synonyms":[],"antonyms":[]},{"definition":"Generous or noble in character.","synonyms":[],"antonyms":[],"example":"Handsome is as handsome does."},{"definition":"Ample; moderately large.","synonyms":[],"antonyms":[],"example":"a handsome salary"},{"definition":"(said of things and people) Dexterous; skillful.","synonyms":[],"antonyms":[]}],"synonyms":["hefty","substantial","good-looking","pretty"],"antonyms":[]}],"license":{"name":"CC BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"},"sourceUrls":["https://en.wiktionary.org/wiki/handsome"]}]

I wrote this code to load data and parse the data I want:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

data = [{"word":"handsome","phonetic":"/ˈhæn.səm/","phonetics":[{"text":"/ˈhæn.səm/","audio":"https://api.dictionaryapi.dev/media/pronunciations/en/handsome-uk.mp3","sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=9021972","license":{"name":"BY 3.0 US","url":"https://creativecommons.org/licenses/by/3.0/us"}},{"text":"/ˈhæn.səm/","audio":"https://api.dictionaryapi.dev/media/pronunciations/en/handsome-us.mp3","sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=1648256","license":{"name":"BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"}}],"meanings":[{"partOfSpeech":"verb","definitions":[{"definition":"To render handsome.","synonyms":[],"antonyms":[]}],"synonyms":[],"antonyms":[]},{"partOfSpeech":"adjective","definitions":[{"definition":"(of people, things, etc) Having a good appearance; good-looking.","synonyms":[],"antonyms":[],"example":"a handsome garment, house, tree, or horse"},{"definition":"Good, appealing, appropriate.","synonyms":[],"antonyms":[]},{"definition":"Generous or noble in character.","synonyms":[],"antonyms":[],"example":"Handsome is as handsome does."},{"definition":"Ample; moderately large.","synonyms":[],"antonyms":[],"example":"a handsome salary"},{"definition":"(said of things and people) Dexterous; skillful.","synonyms":[],"antonyms":[]}],"synonyms":["hefty","substantial","good-looking","pretty"],"antonyms":[]}],"license":{"name":"CC BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"},"sourceUrls":["https://en.wiktionary.org/wiki/handsome"]}]
json_load = (json.loads(json_data))
print(json_load['meanings'])

this error is shown: list indices must be integers or slices, not str
. If I add [0] to before [meanings] the problem is solved but I don’t know why should I do that: print(json_load[0]['meanings'])

Also, I have the same problem for the inner levels and I cannot parse the data. If I remove the square brackets from the beginning and end of the JSON string, there is no more need for [0] before [meanings].

What should I do? Do I need to add numbers before keys or do I have to remove square brackets for all levels?

>Solution :

Your API response is wrapped in a list, presumably because it could have returned multiple results.

So yeah, you would "add numbers before keys" (i.e. access the zeroth member of the array); I’d just guard against unexpectedly getting multiple results, and then grab the zeroth one and work on that.

parsed_data = json.loads(json_data)
if len(parsed_data) != 1:
    raise ValueError(f"Oops, got {len(parsed_data)} results!")
first_definition = parsed_data[0]

print(first_definition["word"], "(", first_definition["phonetic"], ")")

for meaning in first_definition["meanings"]:
    print("*", meaning["partOfSpeech"])
    for defn in meaning["definitions"]:
        print("  *", defn["definition"])
    # ... etc...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading