我正试图调用JSON文件,就像你会一个API;然而,我遇到了麻烦。
下面是JSON数据的示例:
{'businessModelInfo': {'52ff2dd1e4b0b193ed664d41': {'parentId': '52ff2cfce4b0b193ed664d1a', 'nodeInfo': {'position': 2, 'description': 'Platform for the security monitoring, detection & prevention of unauthorized access, misuse & modification to the enterprise network'}, 'id': '52ff2dd1e4b0b193ed664d41', 'name': 'Network Security'}, '52ff2df2e4b0b193ed664d43': {'parentId': '52ff2cfce4b0b193ed664d1a', 'nodeInfo': {'position': 212, 'description': 'Application security testing, vulnerability assessment & runtime application protection'}, 'id': '52ff2df2e4b0b193ed664d43', 'name': 'Application Security'}, '52ff2e04e4b0b193ed664d45': {'parentId': '52ff2cfce4b0b193ed664d1a', 'nodeInfo': {'position': 55, 'description': 'Identity & Access Management (IAM) solution for the user login, authentication and authorization'}, 'id': '52ff2e04e4b0b193ed664d45', 'name': 'IAM'}
这里是代码,我试图调用"名称":
with open(r'C:UsersUserNameProjectsproject_onetest.json', 'r') as f:
data = json.loads(f.read())
print(data['name'])
错误:
KeyError: 'name'
我如何获得所有的'parentId', 'name', 'id'和'description'?
由于json是键值对,如果您想调用嵌套的值,您必须像下面这样声明:
# get name of first object
data['businessModelInfo']['52ff2dd1e4b0b193ed664d41']['name']
# get description
data['businessModelInfo']['52ff2dd1e4b0b193ed664d41']['nodeInfo']['description']