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

Python筛选接口返回JSON中Timebefore字段包含指定值报错如何解决?

报错原因

你遇到的TypeError: unhashable type: 'slice'错误由错误的字典操作语法导致:status["TimeBefore": '05-20']这种[键: 值]的写法会被Python解析为切片操作,而字典不支持切片作为索引,因此触发类型错误。你不能用类xpath的文本匹配语法直接操作Python字典。

正确实现代码

要筛选Timebefore字段包含05-20的条目,直接通过字符串包含判断即可,修改后的完整代码如下:

import requests

with requests.Session() as connection:
    connection.headers["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.86 YaBrowser/21.3.0.740 Yowser/2.5 Safari/537.36"
    # 先访问首页获取必要Cookie,避免接口返回403权限错误
    _ = connection.get("https://xueqiu.com")
    user_timeline = connection.get("https://xueqiu.com/v4/statuses/user_timeline.json?page=1&user_id=4357540281").json()
    # 筛选符合条件的条目
    filtered_list = [
        status for status in user_timeline["statuses"] 
        if "05-20" in status.get("Timebefore", "")
    ]
    # 输出筛选结果
    print(filtered_list)
代码说明
  • 通过in关键字判断字符串包含关系,匹配Timebefore字段中存在05-20的条目
  • 使用dict.get()方法读取字段,避免部分条目无对应字段时抛出KeyError异常
  • 注意字段名大小写需和接口返回完全一致,示例中返回的字段名为Timebefore(首字母b小写),不要写错大小写

内容的提问来源于stack exchange,提问作者Joyce

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 13:24:00