[英]how to access the json key using python json?
如何訪問 python 中以下 json 結構中的bg
密鑰?
{
"window" : [
{
"bg" : "#ffffff",
"title" : "Tkinter Design Light Theme"
}
],
"button" : [
{
"bg" : "#8685EF",
"fg" : "#ffffff",
"activebackground" : "#ffffff",
"activteforeground" : "#E3E0F3",
"font" : "monopace",
"boderwidth" : "0"
}
]
}
我試過用
with open('./light.json','r') as file:
data = json.load(file)
color = data['button']
bg = color['bg']
但對我沒有用
謝謝。
你的button
值是一個dict
list
,你應該像這樣得到列表的第一個元素bg = color[0]['bg]
JSON load 將文件的內容反序列化為第一個參數,變成 Python object。這里的 object 是一個字典。 您可以獲得與'button'
鍵關聯的值,該鍵返回字典列表。 因此,您需要在獲取鍵color
的值之前使用索引 0 訪問該列表。
with open('./light.json','r') as file:
data = json.load(file)
color = data['bg']
bg = color[0]['bg'] # change here, index list before accessing dictionary
嘗試這個。
data['button']
是字典列表。 您必須對其進行迭代並打印所需的值。 - bg
import json
with open('./light.json','r') as file:
data = json.loads(file.read())
color = data['button']
for item in color:
print(item['bg'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.