首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >设置simplejson.JSONEncoder.default不工作

设置simplejson.JSONEncoder.default不工作
EN

Stack Overflow用户
提问于 2018-03-08 06:11:11
回答 1查看 1K关注 0票数 2

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

使用cls:

代码语言:javascript
复制
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))

使用默认值:

代码语言:javascript
复制
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。

这是我正在处理的数据的一个示例。

代码语言:javascript
复制
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'
}

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

EN

回答 1

Stack Overflow用户

发布于 2018-03-08 06:40:18

不要通过修补JSONEncoder类来覆盖default编码器函数。正如您所看到的,这不会有任何影响。相反,将适当的函数传递给dump()dumps()

下面是一个演示:

代码语言:javascript
复制
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()

代码语言:javascript
复制
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))
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49162044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档