[英]How to merge 2 different keys and combine their values as a list for JSON Object in python
[英]How to to access different JSON keys?
我有一個 JSON 文件,如下所示,我正在嘗試使用 Python 訪問這些不同的密鑰。
我的JSON文件格式:
{
"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"
}
]
}
我如何訪問t
、 u
和i
鍵?
我試過了:
print(json_file['t'])
沒有任何幫助解決錯誤:
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'
您可以使用 python 的內置 JSON 模塊,並遍歷您的 json object 的spider
鍵。
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'])
嘗試為打印編制索引
print(json_file["spider"][1]["t"])
您可以嘗試循環打印所有
您可以使用 Json 模塊來加載和讀取 json 個文件。 請找到我獲得“t”值的示例。 為“你”和“我”寫同樣的東西。
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()
希望這會有所幫助。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.