Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JSON data into a Python object?

I want 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']) user.name = response['name'] user.username = response['username'] user.save() 
  • 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?
like image 294
Sai Krishna Avatar asked Jul 05 '11 07:07

Sai Krishna


People also ask

What converts .JSON file into a Python object?

Use jsonpickle module to convert JSON data into a custom Python Object. jsonpickle is a Python library designed to work with complex Python Objects. You can use jsonpickle for serialization and deserialization complex Python and JSON Data.

How do I convert JSON to Python?

Parse JSON - Convert from JSON to PythonIf you have a JSON string, you can parse it by using the json. loads() method. The result will be a Python dictionary.

How do you create a JSON object in Python?

In Python, you can create JSON string by simply assigning a valid JSON string literal to a variable, or convert a Python Object to JSON string using json. loads() function.

How do I extract data from a JSON file in Python?

So first thing you need to import the 'json' module into the file. Then create a simple json object string in python and assign it to a variable. Now we will use the loads() function from 'json' module to load the json data from the variable. We store the json data as a string in python with quotes notation.


2 Answers

UPDATE

With Python3, you can do it in one line, using SimpleNamespace and object_hook:

import json from types import SimpleNamespace  data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'  # Parse JSON into an object with attributes corresponding to dict keys. x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d)) print(x.name, x.hometown.name, x.hometown.id) 

OLD ANSWER (Python2)

In Python2, you can do it in one line, using namedtuple and object_hook (but it's very slow with many nested objects):

import json from collections import namedtuple  data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'  # Parse JSON into an object with attributes corresponding to dict keys. x = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values())) print x.name, x.hometown.name, x.hometown.id 

or, to reuse this easily:

def _json_object_hook(d): return namedtuple('X', d.keys())(*d.values()) def json2obj(data): return json.loads(data, object_hook=_json_object_hook)  x = json2obj(data) 

If you want it to handle keys that aren't good attribute names, check out namedtuple's rename parameter.

like image 130
DS. Avatar answered Sep 18 '22 01:09

DS.


Check out the section titled Specializing JSON object decoding in the json module documentation. 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):         self.name = 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)  # -> <type 'type'> 

Update

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.

like image 34
Shakakai Avatar answered Sep 20 '22 01:09

Shakakai