You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:45:08