Python调用日期转换API报错TypeError: string indices must be integers求助
问题排查与修复方案
报错的核心原因出在convert函数里的列表推导式逻辑:你调用的日期转换API返回的JSON结构是单层级字典,不是包含多个结果的数组。你直接遍历字典对象时,循环变量result拿到的是字典的键字符串,用字符串执行['hd']这类字典取值操作,就会触发TypeError: string indices must be integers报错。
另外还存在两个隐性问题需要同步修复:
- 入参如果是整数类型,直接拼接URL会报错
- 原函数返回值的顺序和调用处的变量解构顺序不匹配,会导致后续取值错误
修复后的代码
import urllib.request import json def convert(day, month, year): # 用f-string拼接更稳妥,自动处理参数转字符串的问题 gr_to_hb_url = f'https://www.hebcal.com/converter?cfg=json&gy={year}&gm={month}&gd={day}&g2h=1' with urllib.request.urlopen(gr_to_hb_url) as response: data = response.read() obj = json.loads(data) # 直接从返回字典取对应字段,返回顺序和调用处解构顺序对齐 return (obj['hy'], obj['hm'], obj['hd'])
调用部分不需要修改:
hby, hbm, hbd = convert(prep_day, prep_month, prep_year) print(hby, hbm, hbd)
内容的提问来源于stack exchange,提问作者Shandron
相关产品推荐
相关产品推荐

