JSON Output

By returning a dictionary from your controller methods, you make it possible for TurboGears to dynamically decide how the data should be presented to the browser. Most often, you'll want to return HTML.

When doing modern, interactive web applications ("AJAX"), you often want to send data to the browser in a form that is readily usable by JavaScript. While modern browsers all have some level of support for XML, that support varies in its depth and speed. For this reason, the lightweight JSON format is a good one. The format is native to JavaScript, so it works in all browsers and is very fast for the browser to deal with.

TurboGears makes it easy to return JSON from your methods. You can set format="json" in your call to expose. Another option is to set allow_json=True in your call to expose. Then, if a request comes in with a parameter of "tg_format=json", TurboGears will convert your Python dictionary into the equivalent JSON. If you eval this in the browser, you'll have a hash table of your data, ready to use!

This means that your application can instantly get a usable API in addition to its browser-based interface! You can set tg.allow_json=True in your app.cfg file, and all of your controller methods will output JSON on demand.