Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tornado write a Jsonp object

any idea how to output a JSON object in python using Tornado. Any good examples, tutorial,libraries or one line code which outputs a JSONP object.

like image 696
Gaurav Avatar asked Jul 27 '12 19:07

Gaurav


1 Answers

Tornado provides tornado.escape.json_encode, which simply wraps json on Python 2.6+ or simplejson on Python 2.5. It's simple to use:

from tornado.escape import json_encode
obj = { 
    'foo': 'bar',
     '1': 2,
     'false': True 
    }
self.write(json_encode(obj))

outputs:

{"1": 2, "foo": "bar", "false": true}

For a JSONP response:

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)
like image 187
Cole Maclean Avatar answered Sep 24 '22 09:09

Cole Maclean