Home > Software engineering >  Parsing JSON with Python to retrieve values within a dictionary
Parsing JSON with Python to retrieve values within a dictionary

Time:01-22

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,

CodePudding user response:

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-

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)

data = test_dict['data']['BITCOIN']
print(f"only id = {data['id']}")
print("--------")
for key, value in test_dict['data']['BITCOIN'].items():
    print(key, value)

Output

only id = 15907
--------
id 15907
name HarryPotterObamaSonic10Inu
symbol BITCOIN

CodePudding user response:

for name in test_dict['data']['BITCOIN']:
    print(name)

output

{'BITCOIN': {'id': 15907, 'name': 'HarryPotterObamaSonic10Inu', 'symbol': 'BITCOIN'}}
id
name
symbol

So, if you do name['id'], you will get id in first iteration and in second iteration it will throw error

you can get value of id by:

for key, value in test_dict['data']['BITCOIN'].items():
    if key=='id':
      print(value)
#15907

with comprehension:

[value for key, value in test_dict['data']['BITCOIN'].items() if key=='id']
[15907]

CodePudding user response:

Keys Error

Fellow, test_dict['data]['BITCOIN'] is represented as:

{
'id': 15907,
'name': 'HarryPotterObamaSonic10Inu',
'symbol': 'BITCOIN'
}

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:

print( test_dict['data']['BITCOIN']['id'] )

get rid of for loop.

  • Related