Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON to model a class using Django

I'm trying to get a JSON object like:

{
    "username": "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?

like image 200
cleliodpaula Avatar asked Oct 10 '11 23:10

cleliodpaula


2 Answers

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.

like image 60
nrabinowitz Avatar answered Oct 14 '22 09:10

nrabinowitz


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.

like image 29
cleliodpaula Avatar answered Oct 14 '22 07:10

cleliodpaula