How Do You Read a JSON File to Extract the Value of a Given Key in a JSON File?

Problem scenario
You want to print the value of a given non-nested key in a JSON value. How can Python help you achieve this?

Solution
Here is an illustrative example. Create a file called reader.py with the following lines of code:

import json
with open("first.json", "r") as reading_content:
i = reading_content.read()
j = json.loads(i)
print(j["bird"])

Have the JSON file look like this:

cat first.json
{"bird": {"name": "singy", "species": "sparrow", "amount": "45"}}

Run the program like this (with first.json in the same directory as the Python program): python3 reader.py

Leave a comment

Your email address will not be published. Required fields are marked *