Best and simple way to handle JSON in Django

As part of the application we are developing (with android client and Django server) a json object which contains user name and pass word is sent to server from android client as follows

HttpPost post = new HttpPost(URL);
 /*Adding key value pairs */
 json.put("username", un);
 json.put("password", pwd);

 StringEntity se = new StringEntity(json.toString());
    post.setEntity(se);
    response = client.execute(post);

The response is parsed like this

result = responsetoString(response.getEntity().getContent()); //Converts response to String 

jObject = new JSONObject(result);
 JSONObject post = jObject.getJSONObject("post");
    username = post.getString("username");
    message = post.getString("message");

Hope upto this everything is fine. The problem comes when parsing or sending JSON responses in Django server. Whats the best way to do this?

We tried using SimpleJSON and it turned out not to be so simple as we didn't find any good tutorials or sample code for the same? Are there any python functions similiar to get,put and opt in java for JSON? Any help would be much appreciated..

Answers


Python standard library has JSON load/dump facility: http://docs.python.org/library/json.html


In Python, JSON arrays become lists, and JSON objects become dicts. Other than that, logical mappings are used (string -> unicode, true/false -> True/False, null -> None).


simplejson.loads and simplejson.dumps transform strings to/from python dicts

from django.utils import simplejson

result = simplejson.loads('{"username": "abc", "password": "def"}')

# now just use result like a python dictionary 
username = result.get('username', None)   # pass second parameter as a default

# or catch KeyError
try:
    password = result['password']
except KeyError, e:
    print 'no password'

dumps is pretty straightforward too:

a_dict = {'username':'abc', 'password': 'def'}
json_str = simplejson.dumps(a_dict)
# json_str = '{"username": "abc", "password": "def"}'

Need Your Help

jqgrid setGridParam datatype:local

jquery-plugins jquery jqgrid

I don't want to hit the server and bring back every row when I am paging through the records by using the pager. I read that if I set the datatype = local in the complete blog in the .ajax functio...

Pagination not working using ExtJS 4 and Java REST WS

java javascript grid extjs4 paging

I finished with an application which requires getting data form a REST WS made in Java. The problem is that When I make the pagination in the client side (javascript) it is not working appropriatel...