首页 > 解决方案 > 我无法在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"])

但这给了我一个错误

标签: pythonjson

解决方案


在 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']) 

推荐阅读