为什么在尝试从 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
       
      }
    }

json 文件在上面。我从 json 中删除了很多值,因为它占用了太多空间。我的python代码在下面。

    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)
--------------------------------

这里是 输出 "fetch = pydata["quotes"][0]["USD{xm}"]
类型错误:字符串索引必须是整数"

leehomspeed 回答:为什么在尝试从 api 获取数据时会收到此错误“类型错误:字符串索引必须为整数”?

首先,您在此处发布的 JSON 数据无效。缺少引号和逗号。例如这里"terms": "https://curr。它必须是 "terms": "https://curr","privacy" 相同,"timestamp" 缺少逗号。
在修复 JSON 数据后,我找到了解决方案。您必须使用 data 而不是 pydata。这意味着您必须将 fetch = pydata["quotes"][0]["USD{xm}"] 更改为 fetch = data["quotes"][0]["USD{xm}"]。但这会导致下一个错误,即 KeyError,因为在您提供给我们的 JSON 数据中,"qoutes" 键之后没有数组。所以你必须摆脱这个 [0] 或者 json 数据必须像这样:

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

最后,您只需将 data["quotes"]["USD{xm}"] 更改为 data["quotes"]["USD"+xm],因为当您键入“IMP " 在输入中。
我希望这能解决您的问题。

本文链接:https://www.f2er.com/5389.html

大家都在问