TurboGears - JSON Rendering



The @expose() decorator by default renders html content. However, this can be set to json content type. TurboGears supports json rendering through tg.jsonify.JSONEncoder (**kwargs) class. To render json data simply pass json as content type to expose decorator.

@expose('json')
def jsondata(self, **kwargs):
   return dict(hello = 'World')

If '/jsondata' URL is entered in browser, it will respond by showing −

{"hello": "World"}

jsonp Rendering

jsonp stands for json with padding. It works similar to json output except for the fact that it provides an application/javascript response with a call to a javascript function providing all the values returned by the controller as function arguments.

To enable jsonp rendering you must first append it to the list of required engines inside your application – config/app_cfg.py

base_config.renderers.append('jsonp')

Write your expose decorator as follows −

@expose('json')
@expose('jsonp')
def jsonpdata (self, **kwargs): 
   return dict(hello = 'World')

When accessing /jsonpdata?callback = callme, you should see −

callme({"hello": "World"});
Advertisements