Primal Pappachan
Primal Pappachan

Reputation: 26535

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..

Upvotes: 1

Views: 2016

Answers (3)

james
james

Reputation: 86

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"}'

Upvotes: 1

harto
harto

Reputation: 90513

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

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799150

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).

Upvotes: 1

Related Questions