Google App Engine で JSON 出力

海外のブログを見ていたら,こんな記述をみつけました。

GAE doesn’t include ‘simplejson‘ in the Python container so you are going to have to include it with your application. I downloaded simplejson-1.8.1 and symbolically linked its simplejson directory into my application directory.

そんなことないですよね。 simplejson パッケージが django.utils に含まれているので,次のようにすれば JSON 形式で出力することができます。日本語文字列を含む場合は, ensure_ascii=False とするところがポイント。

# -*- coding: utf-8 -*-
import wsgiref.handlers
from django.utils import simplejson
from google.appengine.ext import webapp

class hoge(webapp.RequestHandler):
    data = {"cancam_models": [{"name": u"蛯原友里", "age": 28},
                              {"name": u"徳澤直子", "age": 23},
                              {"name": u"西山茉希", "age": 22},]}
    self.response.content_type = “application/json”
    simplejson.dump(data, self.response.out, ensure_ascii=False)

また,最後の行を次のようにすると,JSONP 形式で出力できます。

self.response.out.write("%s(%s)" %
    (callback, simplejson.dumps(data, ensure_ascii=False)))


関連リンク:
simplejson - Google Code



Leave a comment


:

:

:

:

このエントリーのはてなブックマーク (-)