often need to convert an object into a standard dictionary for easy serialization. lately this has been using JSON strings for storing.

Short of manual save and load routines that handle the conversion to dict, there are also some approaches that may help automate/simplify the conversion:

convert python object to dictionary


In summary, try looking at:
a = Object()

to see if it has what you need.

Then, the inverse, converting from a dictionary to an object (during loading):

class Struct:
def __init__(self, **entries):

I've been looking into Django more. I was wondering the best way to automatically return the correct response format for any given type of request. Specifically, I'm interested in distinguishing between html and json requests.

In the past I've just appended '/json' to a given url to get json data, but then I was curious how Rails seems to automatically know what the request format was. According to this:


"Rails determines the desired response format from the HTTP Accept header submitted by the client."

It looks like there is similar functionality in Django, but the routing is not as built in as in Rails.


You can use request.is_ajax(). But that requires that the HTTP_X_REQUESTED_WITH header is set. Most JavaScript libraries do this automatically, but if you're using some other type of client, you'll need to make sure it sets it as well. Alternatively, you can pass a querystring such as ?json with the URL and then check request.GET.has_key('json'), which is probably a little more foolproof.

More details are available here: