JSON字典中creation_date值转int/float遇错,求正确实现方法
解决方法
错误原因拆解
- 你用
{scan["creation_date"]}把值包装成了集合(set),而int()函数仅支持字符串、字节类对象或数字作为参数,这就是触发TypeError的核心原因。 ValueError是因为部分场景下creation_date的取值不是数字字符串(比如'local'),直接强制转换会失败。
正确代码实现
基础转换(确保值为数字字符串时)
如果能确认scan["creation_date"]的取值始终是类似"1692376305"的数字字符串,直接去掉多余的大括号执行转换即可:
# 转换为int类型 creation_date_int = int(scan["creation_date"]) # 转换为float类型 creation_date_float = float(scan["creation_date"])
兼容非数字值的健壮写法
如果存在creation_date为非数字字符串的情况,先做合法性判断再转换:
creation_date_str = scan["creation_date"] if creation_date_str.isdigit(): creation_date_int = int(creation_date_str) # 如需转float,替换为以下代码 # creation_date_float = float(creation_date_str) else: # 自定义非数字场景的处理逻辑,比如设为默认值或跳过 creation_date_int = None print(f"无法将值 '{creation_date_str}' 转换为数字类型")
结果验证
转换后可通过打印类型确认效果:
print(type(creation_date_int)) # 输出 <class 'int'>
内容的提问来源于stack exchange,提问作者Caleb VanDenBos
相关产品推荐
相关产品推荐

