python - 我无法在python中加载Json文件
问题描述
我有这个示例 json 文件,但我无法使用我的 json 文件中的密钥。
import json
people_string = """
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
"""
x = json.loads(people_string)
#print(x)
#print(type(x))
for a in x["widget"]:
print(a)
当我运行此代码时,我得到输出:
debug
window
image
text
如何从“窗口”:“标题”访问?
我试过了
for a in x['widget']:
print(a["window"])
但这给了我一个错误
解决方案
在 json.loads() 之后它是一个嵌套字典。
嵌套字典:嵌套字典意味着将一个字典放在另一个字典中。嵌套非常有用,因为我们可以在程序中建模的信息类型得到了极大的扩展。
# Nested dictionary having same keys
Dict = { 'Dict1': {'name': 'Ali', 'age': '19'},
'Dict2': {'name': 'Bob', 'age': '25'}}
# Prints value corresponding to key 'name' in Dict1
print(Dict['Dict1']['name'])
# Prints value corresponding to key 'age' in Dict2
print(Dict['Dict2']['age'])
推荐阅读
- r - 在可折叠树形图(R 包)上显示百分比和计数
- java - 重用 AudioInputStream
- python - 如何使用删除按钮删除特定事件?
- office365 - 使用 Power Automate 在团队组中添加用户时如何在所有专用频道中添加成员
- javascript - 显示一本书的平均价格
- terraform - Terraform 0.13 - 在使用模块计数时,有没有办法确保在重新创建之前删除资源?
- spring-boot - GET 和 POST 的不同身份验证
- python - 按条件行条件对数据框列求和
- java - 为什么java编译器不抱怨“\s”?
- postgresql - 更改触发器中的数据类型