JSON to model a class using Django

I am trying to get a JSON object, for example:

{ "username": "clelio", "name": "Clelio de Paula", } 

and convert it to:

  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 using simplejson and one method called jsonToClass() :

  >>> import simplejson as json >>> u1 = User() >>> u1.jsonToClass(face) >>> u1.save() 

This does not work. What is the easiest way to do what I want?

+8
json python object django
source share
2 answers

You probably want to look at the Django (de) schema for serialization . Given JSON as:

 [ { "model": "myapp.user", "pk": "89900", "fields": { "name": "Clelio de Paula" } } ] 

You can save it as follows:

 from django.core import serializers for deserialized_object in serializers.deserialize("json", data): deserialized_object.save() 

Please note that I believe that you need to use the Django serialization format to use this method, so you may have to configure your JSON accordingly.

+10
source share

I only realized that

 { "username": "clelio", "name": "Clelio de Paula", } 

is a dict () object.

So this is the easiest thing than I thought.

What I need to solve is just

 def jsonToClass(self, aux): self.name = aux['name'] self.username = aux['username'] 

what he.

+4
source share

All Articles