Zach Wild Zach Wild - 4 months ago 19x
JSON Question

How to convert JSON data into a Python object

I want to use Python to convert JSON data into a Python Object.

I receive JSON data objects from the Facebook API, which I want to store in my Database.

My current View in Django ( python ) ( request.POST contains the JSON )->

response = request.POST
user = FbApiUser(user_id = response['id']) = response['name']
user.username = response['username']

This works fine, but how do I handle complex JSON data objects?

Wouldn't it be much better if I could somehow convert this JSON object into a python object for easy use?


Check out the section labeled "Specializing JSON object decoding" in the json module docs ( for Python v2.7.3 )- there's a section on specialized object decoding. You can use that to decode a JSON object into a specific Python type.

Here's an example:

class User(object):
    def __init__(self, name, username): = name
        self.username = username

import json
def object_decoder(obj):
    if '__type__' in obj and obj['__type__'] == 'User':
        return User(obj['name'], obj['username'])
    return obj

json.loads('{"__type__": "User", "name": "John Smith", "username": "jsmith"}', object_hook=object_decoder)

print type(User)
>>>> <class '__restricted__.User'>


If you want to access data in a dictionary via the json module do this:

user = json.loads('{"__type__": "User", "name": "John Smith", "username": "jsmith"}')
print user['name']
print user['username']

Just like a regular dictionary.