TypeError:Python中的字符串索引必须是整数
我想从currency Converter API得到的Json响应中获取键和值。我得到一个错误:“of string index必须是整数”。下面是Python代码、Json中的数据和错误消息TypeError:Python中的字符串索引必须是整数,python,Python,我想从currency Converter API得到的Json响应中获取键和值。我得到一个错误:“of string index必须是整数”。下面是Python代码、Json中的数据和错误消息 import json from urllib.request import urlopen with urlopen ("http://free.currencyconverterapi.com/api/v6/convert?q=ZAR_GBP,ZAR_USD")as response: so
import json
from urllib.request import urlopen
with urlopen ("http://free.currencyconverterapi.com/api/v6/convert?q=ZAR_GBP,ZAR_USD")as response:
source=response.read()
data= json.loads(source)
data=json.dumps(data,indent=2)
print(data)
value= (data['results']['ZAR_GBP']['val'])
print(value)
Json输出为:
{
"query": {
"count": 2
},
"results": {
"ZAR_GBP": {
"id": "ZAR_GBP",
"fr": "ZAR",
"to": "GBP",
"val": 0.056698
},
"ZAR_USD": {
"id": "ZAR_USD",
"val": 0.072289,
"to": "USD",
"fr": "ZAR"
}
}
}
如果我想访问键“val”及其值,这会给我一个错误
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-61-eb4254977d14> in <module>()
5 data= json.loads(source)
6 data=json.dumps(data,indent=2)
----> 7 print (data['results']['ZAR_GBP']['val'])
8
TypeError: string indices must be integers
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在()
5 data=json.loads(源代码)
6 data=json.dumps(数据,缩进=2)
---->7打印(数据['results']['ZAR_GBP']['val'])
8.
TypeError:字符串索引必须是整数
这是因为您正在将json转换为字符串(使用json.dumps),然后尝试通过键访问所述字符串,这显然失败了,因为它不再是json了
如果您删除
data=json.dumps(data,indent=2)
行,它就会起作用。@TeeKimSigaukeMuchini很高兴听到这个消息。请确保将此标记为答案!