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

标签 python encoding simplejson

我试图覆盖 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'
}

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

最佳答案

不要通过对 JSONEncoder 类进行猴子修补来覆盖默认编码器函数。正如您所看到的,这不会有任何影响。相反,将适当的函数传递给 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))

关于python - 设置 simplejson.JSONEncoder.default 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49162044/

相关文章:

Python 列表理解昂贵

python - 如何在qt中设置QPushButton的背景颜色动画?

php - 如何以 www-data 用户身份终止进程

Java InputStream 编码/字符集

python - 如何在 Ubuntu 中安装 GDAL?

java - 从 hex64 转换为 base 64 字符串

node.js - 哪些编码可用 Node.js

python - 解析从 URL 读取的 JSON 时出现问题

python - 在python中解析json字段

python - 非常 simplejson 解码