[Tutor] build a really simple "json" api from a db

Kent Johnson kent37 at tds.net
Mon Jul 30 23:54:27 CEST 2007


Picio wrote:
> Hi Kent, ok I've decided to go through Django. Now the clue is to find
> some simple guide to
> output json from my model and maybe I can benefit also for the url
> dispatcher to map in a clean way the request coming from my ajax app.
> 
> This is what I'd like to do:
> 
> ajax app-> URL -> urls.py -> view.py -> ORM -> db
> 
> then
> 
> view -> json -> ajax app
> 
> The second path is something I really have to figure out!

Here is the way I do it, with the real model name changed to xxx. Here 
is the view:

def as_json(request, xxx_id):
     ''' Return a xxx in JSON format.
         Required this version of django/core/serializers/json.py:
 
http://code.djangoproject.com/browser/django/trunk/django/core/serializers/json.py?rev=5302
     '''
     xxx = Xxx.objects.get(pk=int(xxx_id))
     return HttpResponse(xxx.asJson(), mimetype='application/json')


Here is the asJson() method from the xxx model, slightly edited to 
remove some extra hacks:

     def asJson(self):
         ''' Return a JSON representation of ourself.
         '''
         from django.core import serializers

         # A note about encoding
         # xxx strings are encoded in UTF-8. That is the default 
encoding for
         # a JSON stream, so we just want to preserve the existing 
characters
         # which is what ensure_ascii=False does.
         # If ensure_ascii=True, the individual bytes of the UTF-8 text
         # will be encoded with \u escapes which is not at all correct
         data = serializers.serialize('json', [self], ensure_ascii=False)

         # Strip leading and trailing [] to make it a single xxx
         data = data[1:-1]

         return data


Kent


More information about the Tutor mailing list