简体   繁体   English

python / tornado中的自定义json编码器

[英]custom json encoders in python/tornado

I'm building in tornado (cyclone, actually), and RequestHandler.write is choking on some of my objects. 我正在建造龙卷风(实际上是旋风),而RequestHandler.write阻塞了我的某些对象。 How do I write a JSONencoder for these objects in tornado? 如何在龙卷风中为这些对象编写JSONencoder?

One complication: some of the objects are borrowed from external libraries, so I don't really have access to their constructors. 一种复杂情况是:有些对象是从外部库借用的,所以我实际上没有访问它们的构造函数的权限。

Apologies for not posting code -- I'm just not sure how to begin here. 不公开代码的道歉-我只是不确定如何从这里开始。

Yes, you can change the default encoder, by adding this befor your mainloop 是的,您可以通过在主循环之前添加此代码来更改默认编码器

import json
json._default_encoder = YourJSONEncoder() #patch json

Basically, the answer is that tornado doesn't support custom json formatting, so you have to use the json library. 基本上,答案是龙卷风不支持自定义json格式,因此您必须使用json库。 Here's the code I used in the end: 这是我最后使用的代码:

import json

class MongoEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, ObjectId):
            return str(obj)
        return json.JSONEncoder.default(self, obj)

print json.dumps(my_mong_obj, cls=MongoEncoder, indent=2)

For datetime object with json formatting it would looks like this 对于具有json格式的datetime对象,它看起来像这样

    import json

    dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime) else None
    response = json.dumps(data, ensure_ascii=False, default=dthandler)

here's my monkey patch: 这是我的猴子补丁:

import json, datetime
from tornado import escape
DT_HANDLER = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) or     isinstance(obj, datetime.date) else None
def json_encode(value):
    return json.dumps(value, default=DT_HANDLER).replace("</", "<\/")

escape.json_encode = json_encode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM