self.write(json.dumps(content, default=json_util.default))
Don't forget the header:
self.set_header("Content-Type", "application/json")
Russ,
I'd love to see what you end up with. Unfortunately, monkey-patching tornado.escape._json_encode to be an extended json.JSONEncoder (to get, e.g., serialization of datetimes and MongoDB ObjectIDs) is exactly what I settled on in this situation.
Cheers,
Ed
On Monday, July 9, 2012 7:01:30 PM UTC-5, Russ Weeks wrote:
Hi, Jorge,Thanks, but that's the problem - I emit a JSON response from a bunch of different request handlers and I know I _will_ forget at some point. But the implementation of RequestHandler.write seems to be pretty simple, so I guess my best bet is to redefine .write in my base RequestHandler subclass and customize the json encoding behaviour there (invoking json.dumps, as you say). Probably beats monkey-patching escape.json_encode or whatever.Thanks again,
-Russ
On Mon, Jul 9, 2012 at 4:35 PM, Jorge Puente Sarrín wrote:
Don't forget the header:
self.set_header("Content-Type", "application/json")
2012/7/9 Jorge Puente Sarrín
Hi Russ,
I assume you're using MongoDB, you can to use json_utils from pymongo.
self.write(json.dumps(content, default=json_util.default))
Regards.
2012/7/9 Russ WeeksHi, folks,
I love the simplicity of passing a dict into RequestHandler.write and having JSON come out the other end. But for me, sometimes the default JSON encoder is a little too strict. When I serialize json using json.dumps from the standard library, I can specify a default encoder to eg. serialize a datetime or a mongo ObjectID as a string. This is useful to me because I don't need JSON to be a robust data transfer format, I just need to produce something that the browser can render.Can anybody suggest a minimally-hacky way for me to get this "lossy encoding" functionality into escape.json_encode? I'd like to continue using RequestHandler.write, for consistency and so I don't have to remember to explicitly set the Content-Type.Thanks,-Russ
--
Atte.
Jorge Puente Sarrín.
In [1]: import tornado.escape
In [2]: tornado.escape.json_encode({'a': 1})
Out[2]: '{"a": 1}'
In [3]: import ujson
In [4]: tornado.escape.JSON.configure(ujson.loads, ujson.dumps)
In [5]: tornado.escape.json_encode({'a': 1})
Out[5]: '{"a":1}'
Lorenzo,
How to extend ujson for to include default parameter in dumps function? and to include object_hook to loads function?
Also note that since the first message in this thread was about
encoding datetimes, customizing json encoding at the handler level
rather than globally allows you to encode datetimes in a locale-aware
way.