简体   繁体   中英

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

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

I want to print the result

Timothy 

What am I missing?

do it one key at a time rather than trying to fit both the keys into one set of quotes as you originally had.

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

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"]

例子

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM