Home > database >  I get an error while trying to read this dictionary
I get an error while trying to read this dictionary

Time:09-29

I get this api response from coinbase

json_response = {"ask":"19540.18","bid":"19538.23","volume":"46199.99613583","trade_id":420452773,"price":"19539.07","size":"0.00091338","time":"2022-09-28T16:44:27.381482Z"}

and when i try to get the "ask" data by using

print(json_response["ask"])

i get the error

Traceback (most recent call last):
print(json_response["ask"])
TypeError: string indices must be integers

I read on W3schools and this works for them. Thanks in advance

CodePudding user response:

The error message is leading you towards the right approach:

String indices must be integers

i.e, you are trying to index into a string, not a dictionary as you think. One way to approach this is by parsing the response string into a dictionary first:

import json

data = json.loads(json_response)
print(Type(data))
print(Type(json_response))

print(data['ask']) #should get you the expected result
 

CodePudding user response:

Your API response is being stored in a list, not a dictionary.

Hence the reason you are getting the error is because json_response can only be accessed using indices.

You need to convert your list of items into a dictionary first. One way to do that:

    json_response = {"ask":"19540.18","bid":"19538.23","volume":"46199.99613583","trade_id":420452773,"price":"19539.07","size":"0.00091338","time":"2022-09-28T16:44:27.381482Z"}
    json_response_dict = dict()

    for key in json_response:
        json_response_dict[key] = json_response[key]

Then this code will appropriately convert the list into a useable dictionary and the following code:

    print(json_response_dict)
    print(json_response_dict["ask"])

Will work and print:

    {'ask': '19540.18', 'bid': '19538.23', 'volume': '46199.99613583', 'trade_id': 420452773, 'price': '19539.07', 'size': '0.00091338', 'time': '2022-09-28T16:44:27.381482Z'}
    19540.18

    
  • Related