JSON to model a class using Django
I'm trying to get a JSON object like:
{
"username":开发者_StackOverflow "clelio",
"name": "Clelio de Paula",
}
and transform it in:
class User(models.Model):
name = models.CharField(max_length=30)
username = models.CharField(max_length=20)
def jsonToClass(s):
aux = json.dumps(s, self)
self.name = aux['name']
self.id = aux['id']
So I tried to use the simplejson
and one method called jsonToClass()
:
>>> import simplejson as json
>>> u1 = User()
>>> u1.jsonToClass(face)
>>> u1.save()
This doesn't work. What is the easiest method to do what I want?
You probably want to look at Django's (de)serialization framework. Given JSON like:
[
{
"model": "myapp.user",
"pk": "89900",
"fields": {
"name": "Clelio de Paula"
}
}
]
you can save it like this:
from django.core import serializers
for deserialized_object in serializers.deserialize("json", data):
deserialized_object.save()
Note that I believe you have to use the Django serialization format to use this method, so you might have to adjust your JSON accordingly.
I just realized that
{
"username": "clelio",
"name": "Clelio de Paula",
}
is a dict() object.
So, this is easiest than I thought.
What I need to solve is just
def jsonToClass(self, aux):
self.name = aux['name']
self.username = aux['username']
that's it.
This is simply achieved as follows:
data = {
"username": "stackExchange",
"name": "stack overflow"
}
for obj in serializers.deserialize("json", data):
do_something_with(obj)
Check out django docs for details
精彩评论