Skip to main content
 首页 » 编程设计

python之设置 simplejson.JSONEncoder.default 不起作用

2024年09月07日8luoye11

我正在尝试否决 simplejson 的默认编码器。我尝试了两种方法。

使用类:

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' 
} 

谁能帮我解决这个令人抓狂的问题?

请您参考如下方法:

不要通过猴子修补 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))