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:

JSON Example
Title: <input type="text" name="title">
Author: <input type="text" name="author">
<input type="submit" value="post" name="Submit"/>

view raw
hosted with ❤ by GitHub

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

view raw
hosted with ❤ by GitHub

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 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 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']

view raw
hosted with ❤ by GitHub

Leave a Reply

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