I am trying to parse JSON and retrieve a certain value (ID) but I am getting the following error:
TypeError: string indices must be integers
The following is my code and JSON:
import json
# JSON string
info_symbol = '{"status":{"timestamp":"2023-01-21T15:18:43.937Z","error_code":0,"error_message":null,"elapsed":21,"credit_count":1,"notice":null},"data":{"BITCOIN":{"id":15907,"name":"HarryPotterObamaSonic10Inu","symbol":"BITCOIN"}}}'
# Convert string to Python dict
test_dict = json.loads(info_symbol)
print(test_dict['data'])
for name in test_dict['data']['BITCOIN']:
print(name['id'])
Id like to grab solely the ID – so: 15907
"id":15907,
3
Answers
You don’t need the looping in that case to get only the
id
. If you need all the key and values from the dictionary then you can iterate like below-Output
output
So, if you do
name['id']
, you will getid
in first iteration and in second iteration it will throw erroryou can get value of id by:
with comprehension:
Keys Error
Fellow,
test_dict['data]['BITCOIN']
is represented as:Your are iterating the above dictionary, so when you
print(name[id])
,name
iterator take the key:Value of id, name, and symbol.Literally tour code is accesing as
id.['id'], name.['id'], symbol.['id]'.
SOLUTION
just access to the id adding one more bracket:
get rid of for loop.