Json have been already presented by Fabio Fucci on this blog. Django is a python framework for web application, which supports json thru a library.
We’re going to create a simple request-response application:
- request is issued by dojo.xhrPost;
- response is managed by python.
Creating a request means creating a json string to send to the server.
/* create the variable to post */
var arguments={'user':'ioggstream','status':'at work'};
dojo.xhrPost({
url: '/json/post',
handleAs: "json",
/* serialize the argument object to a json string*/
postData: dojo.toJson(arguments),
load: function(data) {
alert(data.result);
},
error: function(error) {
alert("An unexpected error occurred: " + error);
}
});
Now that the request is issued, and the postData is a json string, we use python to de-serialize the string to a python object.
The dict() python class – aka dictionary – is an associative array. The django.simplejson can serialize and deserialize object using dict().
Let’s see the code
from django.utils import simplejson
from google.appengine.ext import webapp
class JsonService(webapp.RequestHandler):
def post(self):
logging.info("manage a POST request")
# parse request body to a python dict() object
args = simplejson.loads(self.request.body)
# returning request in a verbose mode
# creating a dict() object with default message
message = {'result':'The request misses user and/or    status'}
if 'user' in args and 'status in args:
message['result'] = "The request user %s status is %s " % (args['user'], args['status'])
# return the serialized object message
return simplejson.dumps(message)