Making Calls to a JSON file

Question:

I am trying to make calls to a JSON file like you would an API; however, I am having trouble.

Here is a sample of the JSON data:

{'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'}

Here is the code I’m trying to call the "name" with:

with open(r'C:UsersUserNameProjectsproject_onetest.json', 'r') as f:
    data = json.loads(f.read())
    print(data['name'])

Error:

KeyError: 'name'

How would I obtain all the ‘parentId’, ‘name’, ‘id’, and ‘description’?

Asked By: BQuist

||

Answers:

As json is key-value pair, if you want to call the nested value, you have to state like below:

# get name of first object
data['businessModelInfo']['52ff2dd1e4b0b193ed664d41']['name']

# get description
data['businessModelInfo']['52ff2dd1e4b0b193ed664d41']['nodeInfo']['description']
Answered By: Whitney Liao
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.