如何将整数字符串转换为整数? 导入json 类解码器(json.JSONDecoder): def解码(自身): 结果=超级(解码器,自身)。解码(s) 返回自解码(结果) def_解码(自身,o): 如果isinstance(o,str)或isinstance(o,unicode): 尝试: 返回整数(o) 除值错误外: 尝试: 返回浮动(o) 除值错误外: 返回o elif isinstance(o,dict): 返回{k:self.\u在o.items()中为k,v解码(v)} elif isinstance(o,列表): 返回[self.\u解码(v)为v输入o] 其他: 返回o 将open('data.json')作为f: data=json.load(f,cls=Decoder) **错误代码为:** 回溯(最近一次呼叫最后一次): 文件“\\Program:(c)\Folder\sample\pyhton\sample.py”,第29行,在 data=json.load(f,cls=Decoder) 文件“C:\Program Files(x86)\Python36-32\lib\json\\ u_init\u_.py”,第348行,加载 'not{!r}'。格式(s._类_._名称__;)) TypeError:JSON对象必须是str、bytes或bytearray,而不是“TextIOWrapper”
Python版本:3.6.4 如何解决此错误 我正在尝试使用类将字符串整数转换为整数 问候,,如何将整数字符串转换为整数? 导入json 类解码器(json.JSONDecoder): def解码(自身): 结果=超级(解码器,自身)。解码(s) 返回自解码(结果) def_解码(自身,o): 如果isinstance(o,str)或isinstance(o,unicode): 尝试: 返回整数(o) 除值错误外: 尝试: 返回浮动(o) 除值错误外: 返回o elif isinstance(o,dict): 返回{k:self.\u在o.items()中为k,v解码(v)} elif isinstance(o,列表): 返回[self.\u解码(v)为v输入o] 其他: 返回o 将open('data.json')作为f: data=json.load(f,cls=Decoder) **错误代码为:** 回溯(最近一次呼叫最后一次): 文件“\\Program:(c)\Folder\sample\pyhton\sample.py”,第29行,在 data=json.load(f,cls=Decoder) 文件“C:\Program Files(x86)\Python36-32\lib\json\\ u_init\u_.py”,第348行,加载 'not{!r}'。格式(s._类_._名称__;)) TypeError:JSON对象必须是str、bytes或bytearray,而不是“TextIOWrapper”,python,json,Python,Json,Python版本:3.6.4 如何解决此错误 我正在尝试使用类将字符串整数转换为整数 问候,, Sriramjson.loads用于加载json字符串 使用此转换表将s(包含JSON文档的str、bytes或bytearray实例)反序列化为Python对象。() 要加载json文件,您需要data=json.load(f,cls=Decoder)(注意缺少的s) 使用此转换表将fp(a.read()-支持包含JSON文档的文本文件或二进制文件)反序列化为Python对象。() 在您的情况下,您
Sriram
json.loads
用于加载json字符串
使用此转换表将s(包含JSON文档的str、bytes或bytearray实例)反序列化为Python对象。()
要加载json文件,您需要data=json.load(f,cls=Decoder)
(注意缺少的s)
使用此转换表将fp(a.read()-支持包含JSON文档的文本文件或二进制文件)反序列化为Python对象。()
在您的情况下,您甚至不需要自定义解码器,因为json
模块将自动为您转换浮点和整数:
import json
class Decoder(json.JSONDecoder):
def decode(self, s):
result = super(Decoder, self).decode(s)
return self._decode(result)
def _decode(self, o):
if isinstance(o, str) or isinstance(o, unicode):
try:
return int(o)
except ValueError:
try:
return float(o)
except ValueError:
return o
elif isinstance(o, dict):
return {k: self._decode(v) for k, v in o.items()}
elif isinstance(o, list):
return [self._decode(v) for v in o]
else:
return o
With open('data.json') as f:
data = json.loads(f,cls=Decoder)
**Error code is:**
Traceback (most recent call last):
File "\\Program:(c)\Folder\sample\pyhton\sample.py", line 29, in <module>
data = json.loads(f,cls=Decoder)
File "C:\Program Files (x86)\Python36-32\lib\json\__init__.py", line 348, in loads
'not {!r}'.format(s.__class__.__name__))
TypeError: the JSON object must be str, bytes or bytearray, not 'TextIOWrapper'
因此,这样做就足够了:
>>> import json
>>> json.loads('{"a": 0.254}')
{'a': 0.254}
data = json.load(f)