Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract key value from JSON using python NameError

I am creating a python script to extract values, Name from the JSON Key Details from the JSON result. Python error mentioned KeyError ‘details[name]’. The JSON example is found below. The JSON is incomplete. JSON has other data which I am not going to put it here as it is confidential.

details: {'id': 5555, 'name': 'Timothy', 'Gender': 'Male'}

My Python script is shown below

print(json_data['details[name]'])

Error Message

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

print(json_data['details[name]'])
KeyError: 'details[name]'

I want to print the result

Timothy 

What am I missing?

>Solution :

Assuming json_data is the name you’ve chosen for the entirety of the JSON object, you need provide a proper index for json_data in your print statement. Your current index is a string because you’ve captured your brackets inside of the apostrophes. The way you’re indexing the JSON object is also incorrect.

JSON objects are essentially multidimensional dictionaries. The way you print the value of a value of a key is like this: print(dict["key"]["value"]).

Assuming the details key is also a string, the correct way to print the value of name from the key "details" is: print(json_data["details"]["name"]

Example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading