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}"]
TypeError:字符串索引必须是整数">
<代码>代码>
首先,你在这里发布的JSON数据是无效的。缺少引号和逗号。比如这里的"terms": "https://curr",
。它一定是"privacy"
。"timestamp"
也是一样,data
缺少一个逗号。
我修复JSON数据后,我找到了一个解决方案。你必须使用pydata
而不是fetch = pydata["quotes"][0]["USD{xm}"]
。这意味着必须将fetch = data["quotes"][0]["USD{xm}"]
更改为"qoutes"
。但是这会导致下一个错误,这将是一个KeyError,因为在您提供给我们的JSON数据中,"terms": "https://curr
0键之后没有数组。所以你必须去掉这个data["quotes"]["USD{xm}"]
或者json数据像这样:
PP_4最后,您只需要将data["quotes"]["USD"+xm]
更改为USD{xm}
,因为python试图找到一个名为USDIMP
的键,而不是例如CC_15,当您键入"IMP"在输入中。
我希望这解决了你的问题。