遍历JSON转换的字典时为何报错?string indices must be integers问题排查
Python提取JSON数据报错解决:string indices must be integers, not "str"
我正在学习Python,在获取JSON数据并提取特定值的过程中,遇到了如下错误:
string indices must be integers, not "str".
错误出现在代码最后一行:
print(dollar["rate_float"])
我的原代码如下:
import sys import requests import json if len(sys.argv) != 2: print("Missing command-line argument") # 检查用户是否在程序名后传入参数 elif sys.argv[1].isalpha(): print("Command-line argument is not a number") # 检查用户传入的是否为数字 else: response = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json") # 从coindesk获取JSON数据 data_store = response.json() # 将JSON数据存储到变量data_store中 for dollar in data_store["bpi"]: # 遍历字典提取美元价格 print(dollar["rate_float"])
尝试修改代码后,又出现新错误:name 'bpi' is not defined,修改后的代码片段如下:
# 将JSON数据存储到变量data_store中 for dollar in data_store[bpi.values()]: # 遍历字典提取美元价格 print(dollar[rate_float.values()])
API返回的JSON结构如下:
{ "time": { "updated": "Feb 27, 2024 20:16:10 UTC", "updatedISO": "2024-02-27T20:16:10+00:00", "updateduk": "Feb 27, 2024 at 20:16 GMT" }, "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org", "chartName": "Bitcoin", "bpi": { "USD": { "code": "USD", "symbol": "$", "rate": "57,197.495", "description": "United States Dollar", "rate_float": 57197.4947 }, "GBP": { "code": "GBP", "symbol": "£", "rate": "45,108.976", "description": "British Pound Sterling", "rate_float": 45108.9758 }, "EUR": { "code": "EUR", "symbol": "€", "rate": "52,744.155", "description": "Euro", "rate_float": 52744.1549 } } }
错误原因
- 第一个错误:Python中直接遍历字典(比如
data_store["bpi"])时,默认只会遍历字典的键,也就是"USD"、"GBP"、"EUR"这些字符串。此时循环变量dollar是字符串,自然不能用["rate_float"]这种字符串索引,因此触发string indices must be integers, not "str"错误。 - 第二个错误:修改代码时,把字符串键
"bpi"和"rate_float"写成了未定义的变量bpi、rate_float,Python会把它们当作变量名查找,但你并没有定义这些变量,所以报name 'bpi' is not defined。
正确解决方案
方案1:提取所有货币的rate_float
如果需要获取所有货币的价格,遍历data_store["bpi"]的值即可:
import sys import requests import json if len(sys.argv) != 2: print("Missing command-line argument") elif sys.argv[1].isalpha(): print("Command-line argument is not a number") else: response = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json") data_store = response.json() # 遍历bpi字典的所有值(每个值是对应货币的详情字典) for currency in data_store["bpi"].values(): print(currency["rate_float"])
方案2:只提取美元的rate_float
如果只需要美元价格,不用循环,直接通过键层级取值:
import sys import requests import json if len(sys.argv) != 2: print("Missing command-line argument") elif sys.argv[1].isalpha(): print("Command-line argument is not a number") else: response = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json") data_store = response.json() # 直接通过键层级获取USD的rate_float dollar_rate = data_store["bpi"]["USD"]["rate_float"] print(dollar_rate)
内容的提问来源于stack exchange,提问作者Elvino Michel
相关产品推荐
相关产品推荐

