Tornado提供了tornado.escape.json_encode
,可将其简单地包装json
在Python 2.6+或simplejson
Python 2.5上。使用简单:
from tornado.escape import json_encode
obj = {
'foo': 'bar',
'1': 2,
'false': True
}
self.write(json_encode(obj))
输出:
{"1": 2, "foo": "bar", "false": true}
对于JSONP响应:
callback = self.get_argument('callback')
jsonp = "{jsfunc}({json});".format(jsfunc=callback,
json=json_encode(obj))
self.set_header('Content-Type', 'application/javascript')
self.write(jsonp)