I'm building in tornado (cyclone, actually), and RequestHandler.write is choking on some of my objects. How do I write a JSONencoder for these objects in tornado?
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. 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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.