问题描述
我想使用Python将JSON数据转换为Python对象。我收到来自Facebook API的JSON数据对象,我想存储在我的数据库中。
我目前在Django(Python)中查看( request.POST
包含JSON):
response = request.POST
user = FbApiUser(user_id = response ['id'])
user.name = response ['name']
user.username = response ['username']
user.save()
-
这样做很好,但是如何处理复杂的JSON数据对象?
-
如果我能以某种方式将这个JSON对象转换成Python对象,以方便使用,那不会好多了?
查看json模块文档中标有专用JSON对象解码的部分( for Python v2.7.3) - 有一个专门的对象解码部分。您可以使用它将JSON对象解码为特定的Python类型。
以下是一个示例:
class User(object):
def __init __(self,name,username):
self.name = name
self。 username = username
import json
def object_decoder(obj):
如果obj和obj中的'__type__'['__ type__'] =='User':
return User(obj ['name'],obj ['username'])
return obj
json.loads('{__ type__:User,name John Smith,username:jsmith}',object_hook = object_decoder)
打印类型(用户)
>>>> < class'__restricted __。User'>
更新
如果要通过json模块访问字典中的数据,请执行以下操作:
user = json.loads('{ __type__:User,name:John Smith,username:jsmith}')
print user ['name']
print user ['username']
就像一个常规字典。
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?
Check out the section labeled "Specializing JSON object decoding" in the json module docs ( http://docs.python.org/library/json.html 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):
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)
>>>> <class '__restricted__.User'>
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.
这篇关于如何将JSON数据转换为Python对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!