| 1 |
.. _jsonify: |
| 2 |
|
| 3 |
|
| 4 |
JSON Serialization |
| 5 |
================== |
| 6 |
|
| 7 |
Pecan includes a simple, easy-to-use system for generating and serving |
| 8 |
JSON. To get started, create a file in your project called |
| 9 |
``json.py`` and import it in your project's ``app.py``. |
| 10 |
|
| 11 |
Your ``json`` module will contain a series of rules for generating |
| 12 |
JSON from objects you return in your controller. |
| 13 |
|
| 14 |
Let's say that we have a controller in our Pecan application which |
| 15 |
we want to use to return JSON output for a :class:`User` object:: |
| 16 |
|
| 17 |
from myproject.lib import get_current_user |
| 18 |
|
| 19 |
class UsersController(object): |
| 20 |
@expose('json') |
| 21 |
def current_user(self): |
| 22 |
''' |
| 23 |
return an instance of myproject.model.User which represents |
| 24 |
the current authenticated user |
| 25 |
''' |
| 26 |
return get_current_user() |
| 27 |
|
| 28 |
In order for this controller to function, Pecan will need to know how to |
| 29 |
convert the :class:`User` object into data types compatible with JSON. One |
| 30 |
way to tell Pecan how to convert an object into JSON is to define a |
| 31 |
rule in your ``json.py``:: |
| 32 |
|
| 33 |
from pecan.jsonify import jsonify |
| 34 |
from myproject import model |
| 35 |
|
| 36 |
@jsonify.register(model.User) |
| 37 |
def jsonify_user(user): |
| 38 |
return dict( |
| 39 |
name = user.name, |
| 40 |
email = user.email, |
| 41 |
birthday = user.birthday.isoformat() |
| 42 |
) |
| 43 |
|
| 44 |
In this example, when an instance of the :class:`model.User` class is |
| 45 |
returned from a controller which is configured to return JSON, the |
| 46 |
:func:`jsonify_user` rule will be called to convert the object to |
| 47 |
JSON-compatible data. Note that the rule does not generate a JSON |
| 48 |
string, but rather generates a Python dictionary which contains only |
| 49 |
JSON friendly data types. |
| 50 |
|
| 51 |
Alternatively, the rule can be specified on the object itself, by |
| 52 |
specifying a :func:`__json__` method in the class:: |
| 53 |
|
| 54 |
class User(object): |
| 55 |
def __init__(self, name, email, birthday): |
| 56 |
self.name = name |
| 57 |
self.email = email |
| 58 |
self.birthday = birthday |
| 59 |
|
| 60 |
def __json__(self): |
| 61 |
return dict( |
| 62 |
name = self.name, |
| 63 |
email = self.email, |
| 64 |
birthday = self.birthday.isoformat() |
| 65 |
) |
| 66 |
|
| 67 |
The benefit of using a ``json.py`` module is having all of your JSON |
| 68 |
rules defined in a central location, but some projects prefer the |
| 69 |
simplicity of keeping the JSON rules attached directly to their |
| 70 |
model objects. |