Tornado – Escape – Json

Tornado web server exports methods for escape/unescape html, xml, Json among others. This blog discusses about encoding and decoding JSON format.

Tornado has the following methods:

  • tornado.escape.json_encode(value) – JSON’ify the Python object passed to it as argument
  • tornado.escape.json_decode(value) – Converts the JSON string into Python Object

Here’s a usage example:


<html>
<title>
JSON Example
</title>
<body>
<FORM ACTION="/blog" METHOD=POST>
Title: <input type="text" name="title">
Author: <input type="text" name="author">
<input type="submit" value="post" name="Submit"/>
</FORM>
</body>
</html>

view raw

jsonform.html

hosted with ❤ by GitHub


import tornado.web
import tornado.escape
import tornado.httpclient
class Blog(tornado.web.RequestHandler):
def get(self):
self.render('jsonform.html')
def post(self):
data_json = tornado.escape.json_encode(self.request.arguments)
self.write(data_json)
## handles client request
class Language(tornado.web.RequestHandler):
def get(self):
data = {'py':'Python', 'js':'JavaScript'}
self.set_header('Content-Type', 'text/javascript')
self.write(tornado.escape.json_encode(data))
application = tornado.web.Application([
(r"/blog", Blog),
(r"/lang", Language),
], debug=True)
if __name__ == '__main__':
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()

In this example,

1. When user browses to http://localhost:8888/blog, jsonform.html is rendered that asks for ‘Title’ and ‘Author’

2. On filling this form, a POST request is sent to /blog URL, where the posted arguments are encoded to JSON string with tornado.escape.json_encode() and rendered on the user browser

3. class Language is request handler that caters to http://localhost:8888/lang. In this class, a Python dictionary object is converted to JSON string with tornado.escape.json_encode() and responds with this JSON string to any client request.

4. When tornadojsonclient.py makes a GET request to /lang URL, JSON string is sent as a response. The client decodes this JSON string to a Python dictionary object with tornado.escape.json_decode() method

Code for tornadojsonclient.py below


import tornado.httpclient
http = tornado.httpclient.HTTPClient()
response = http.fetch("http://localhost:8888/lang&quot;)
data = tornado.escape.json_decode(response.body)
print data['py'], data['js']

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.