Home > Mobile >  How to to access different JSON keys?
How to to access different JSON keys?

Time:03-29

I have a JSON file as the following, and I'm trying to access those different keys with Python.

My JSON file format:

{
   "spider":[
      {
         "t":"Spider-Man: No Way Home (2021)",
         "u":"movie\/spider-man-no-way-home-2021",
         "i":"c2NJbHBJYWNtbW1ibW12Tmptb1JjdndhY05FbXZhS1A"
      },
      {
         "t":"Spider-Man: Far from Home (2019)",
         "u":"movie\/spider-man-far-from-home-2019",
         "i":"c2NJbHBJYWNtTGNtdm1qbXZtYm1FRWNtcEV4bWJ4bWJteGo"
      },
      {
         "t":"Spider-Man: Homecoming (2017)",
         "u":"movie\/spider-man-homecoming-2017",
         "i":"c2NJbHBJYWN2TllqbVRibXVjbWJ2d3h2dGNtam1idmM"
      },
      {
         "t":"Spider-Man: Into the Spider-Verse (2018)",
         "u":"movie\/spider-man-into-the-spider-verse-2018",
         "i":"c2NJbHBJYWNtVEVtdnZjbXZtdm1qRWNtYnhtR1VURXZjY3c"
      },
      {
         "t":"Spider-Man (2002)",
         "u":"movie\/spider-man-2002",
         "i":"c2NJbHBJYWNtam1ZanZjbWptakVjbXZtdm1oenh2Y3htSQ"
      },
      {
         "t":"The Spiderwick Chronicles (2008)",
         "u":"movie\/the-spiderwick-chronicles-2008",
         "i":"c2NJbHBJYWNtVG9Oam1qbWJFY21ibWJ2d1BtYm1tbUhj"
      }
   ]
}

How I can access the t, u, and i keys?

I tried:

print(json_file['t'])

Nothing helped with the error:

Traceback (most recent call last):
  File "/home/werz/Desktop/trying/programming/nutflix/flask-nutflix/test.py", line 38, in <module>
    print (json_file['t'])
KeyError: 't'

CodePudding user response:

Try indexing for printing like

    print(json_file["spider"][1]["t"])

You can try for loop to print all

CodePudding user response:

You can use python's builtin JSON module, and iterate through the spider key of your json object.

import json#import the builtin json library

with open('file_path') as file:#open the file
  text=f.read()#read the contents of the file
  json_data=json.loads(text)#turn the file into a json object
  t=[]#List of the t 
  u=[]#List of the u 
  i=[]#List of the i
  for film in json_data['spider']:#iterate through films
    t.append(film['t'])#store the data for these films
    u.append(film['u'])
    i.append(film['i'])

CodePudding user response:

You can use Json module to load and read json files. Please find the example where i am getting 't' values. Write the same for 'u' and 'i'.

import json

# Opening JSON file
f = open('myJson.json', )

# returns JSON object as a dictionary
data = json.load(f)

# Iterating through the json list
for i in data['spider'][:]:
    print(i['t'])

# Closing file
f.close()

Hope this will help. :)

  • Related