0 votes
1 view
in Python by (47.8k points)

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']) 

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?

1 Answer

0 votes
by (107k points)

To convert JSON data into a Python object you can do it in one line, using namedtuple and object_hook:-

import json 

from collections import namedtuple 

data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'

x = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values())) 

print(x.name, x.hometown.name, x.hometown.id)

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

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
+2 votes
2 answers
0 votes
1 answer
asked Oct 27, 2019 in Java by Shubham (3.9k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...