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

Python统计JSON文件userID唯一值及TypeError报错解决

错误原因

你遇到的报错是因为你将写入模式打开的文件对象当成了已解析的JSON数据来操作,同时存在其他几个逻辑问题:

  • 第二个with语句中打开的file是文件IO对象,没有["UserID"]这种下标访问方式,你要操作的是之前已经解析完成的JSON数组
  • 字段名大小写不匹配:JSON中的键是小写开头的userID,你代码中写的是大写开头的UserID,取值会失败
  • 统计逻辑位置错误:统计唯一值的代码不需要放在文件写入的with块中,直接操作已加载到内存的JSON数组即可
  • 冗余代码:with语句会自动关闭文件,不需要手动写f.close,且你写的f.close缺少括号不会生效
修正后完整代码
import json
to_queue = []
def structure_json():
    # 处理原文件格式问题,转换为标准JSON数组
    with open("file.json", "r+") as f:
        old = f.read()
        new = old.replace('}{', '},{')
        tmps = '[' + new + ']'
        json_data = json.loads(tmps)
        for item in json_data:
            to_queue.append(item)
    
    # 写入格式化后的新文件
    with open('update_2.json', 'w') as file:
        json.dump(json_data, file, indent=2)
    
    # 统计userID唯一值(用set自动去重,效率更高)
    unique_user_ids = set()
    for item in json_data:
        # 兼容部分对象没有userID字段的情况
        user_id = item.get("userID", "")
        unique_user_ids.add(user_id)
    
    # 打印结果
    print("userID唯一值列表:", list(unique_user_ids))
    print("userID唯一值数量:", len(unique_user_ids))

structure_json()
效果说明

如果使用你给出的示例JSON文件运行代码,所有userID都是空字符串,最终会输出唯一值数量为1;如果原文件中存在不同的userID值,会自动去重统计正确数量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:06:03