How Do You Use Python to Create a Tuple with Extracted and Nested Values from JSON Files?

Problem scenario
You have some JSON files like this:

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


$ cat second.json
{"bird": {"name": "flighty", "species": "seagull", "amount": "21"}}

Within the "bird" key there are other keys. How do you create a tuple with the species values?

Solution
Place first.json, second.json and the Python program below (called reader.py) in the same directory.

Run reader.py (with python3 reader.py):

import json

lof = ("first.json", "second.json")
counter = 0
t = ()

for x in lof:
  counter = counter + 1
  with open(x, "r") as reading_content:
      i = reading_content.read()
      j = json.loads(i)
      k = j["bird"]
      l = k["species"]
      subtup = (l,)
      t = t + subtup;

print(t)

Leave a comment

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