我正在尝试否决simplejson的默认编码器。我尝试了两种方法。
使用cls:
class ExtendedJSONEncoder(simplejson.JSONEncoder):
def default(self, obj):
if isinstance(obj, float):
return '{0:.8f}'.format(obj)
return super(ExtendedJSONEncoder, self).default(obj)
def save_signal(self, signal):
with open('test.json', 'w') as outfile:
outfile.write(simplejson.dumps(signal, cls=ExtendedJSONEncoder))使用默认值:
def extended_JSONEncoder(obj):
if isinstance(obj, float):
return '{0:.8f}'.format(obj)
return simplejson.JSONEncoder.default(obj)
def save_signal(self, signal):
with open('test.json', 'w') as outfile:
outfile.write(simplejson.dumps(signal, default=extended_JSONEncoder))在这两种情况下,都不会调用扩展的JSONEncoder。
这是我正在处理的数据的一个示例。
signal = {
'pair': 'BTC-XRP',
'term': None,
'exchange': None,
'entry_min': 8.5e-05,
'entry_max': None,
'stop_loss': None,
'targets': [9.4e-05, 0.000105, 0.000118],
'risk': 'medium',
'strategy': 'targets',
'enabled': True,
'test_mode': False,
'msg_id': 214,
'msg_timestamp': '2018-03-05 20:01:52',
'channel_id': '1234',
'channel_name': 'realtime_sig'
}有人能帮我解决这个令人抓狂的问题吗?
发布于 2018-03-08 06:40:18
不要通过修补JSONEncoder类来覆盖default编码器函数。正如您所看到的,这不会有任何影响。相反,将适当的函数传递给dump()或dumps()。
下面是一个演示:
import simplejson
class C:
def __init__(self, item):
self.item = item
def json_encoder(obj):
print("WooWoo! Called!", obj)
if isinstance(obj, C):
return obj.item
raise TypeError(repr(obj) + " is not JSON serializable")
with open('save.json', 'w') as outfile:
outfile.write(simplejson.dumps([1,C(47),C('orange'),4], default=json_encoder))另一种不推荐使用的方法是将JSONEncoder子类化,然后通过cls参数将生成的类传递给dumps()。
import simplejson
class C:
def __init__(self, item):
self.item = item
class json_encoder(simplejson.JSONEncoder):
def default(self, obj):
print("WooWoo! Called!", obj)
if isinstance(obj, C):
return obj.item
raise TypeError(repr(obj) + " is not JSON serializable")
with open('save.json', 'w') as outfile:
outfile.write(simplejson.dumps([1,C(47),C('orange'),4], cls=json_encoder))https://stackoverflow.com/questions/49162044
复制相似问题