Alois
Alois

Reputation: 23

Why am I getting this error "TypeError: string indices must be integers" when trying to fetch data from an api?

json file = 
    {
      "success": true,
      "terms": "https://curr
      "privacy": "https://cu
      "timestamp": 162764598
      "source": "USD",
      "quotes": {
        "USDIMP": 0.722761,
        "USDINR": 74.398905,
        "USDIQD": 1458.90221
       
      }
    }

The json file is above. i deleted lot of values from the json as it took too many spaces. My python code is in below.

    import urllib.request, urllib.parse, urllib.error
    
    import json
    
    response = "http://api.currencylayer.com/live?access_key="
    
    api_key = "42141e*********************"
    parms = dict()
    
    
    
    parms['key'] = api_key
    url = response + urllib.parse.urlencode(parms)
    mh = urllib.request.urlopen(url)    
    source = mh.read().decode()
    
    data = json.loads(source)
    pydata = json.dumps(data, indent=2)
    
    print("which curreny do you want to convert USD to?")
    xm = input('>')
    print(f"Hoe many USD do you want to convert{xm}to")
    value = input('>')
    
    fetch = pydata["quotes"][0]["USD{xm}"]
    
    answer = fetch*value 
    
    print(fetch)
--------------------------------

Here is the output "fetch = pydata["quotes"][0]["USD{xm}"]
TypeError: string indices must be integers"

Upvotes: 1

Views: 365

Answers (1)

Felix
Felix

Reputation: 66

First of all the JSON data you posted here is not valid. There are missing quotes and commas. For example here "terms": "https://curr. It has to be "terms": "https://curr",. The same at "privacy" and the "timestamp" is missing a comma.
After i fixed the JSON data I found a solution. You have to use data not pydata. This mean you have to change fetch = pydata["quotes"][0]["USD{xm}"] to fetch = data["quotes"][0]["USD{xm}"]. But this would result in the next error, which would be a KeyError, because in the JSON data you provided us there is no array after the "qoutes" key. So you have to get rid of this [0] or the json data has to like this:

"quotes":[{
    "USDIMP": 0.722761,
    "USDINR": 74.398905,
    "USDIQD": 1458.90221
   }]

At the end you only have to change data["quotes"]["USD{xm}"] to data["quotes"]["USD"+xm] because python tries to find a key called USD{xm} and not for example USDIMP, when you type "IMP" in the input.
I hope this fixed your problem.

Upvotes: 1

Related Questions