10

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?

3 Answers 3

16

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Well, you could use the json module to wrap the response in the outer array and object required by the serialization module. But that might be overkill.
Thanks @nrabinowitz, I'm going to read the deserialization framework, but I need to get this json objects by http request, and don't has a standard because sometimes I'm getting data using graph.facebook.com and another youtube api.
I should also point out that in your original code, json.dumps() should be json.loads(s) - that's probably why the original code didn't work.
@nrabinowitz The type of deserialized_object is DeserializedObject. How can I convert that into a django model class type. (Assume that the JSON object I want to deserialize is returned by serializing a model object)
3

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.

3 Comments

somewhat dangerous but maybe ok (sometimes) probably should do some checks and whatnot self.__dict__.update(aux)
How is this dangerous? Is it because it might get duplicate keys (and override distinct values) if data isn't checked?
Because you can have fields on your model that are Python properties, and guarded by complex setters. Otherwise, there is no type-checking or validation at all - but if you trust your data , that might work
0

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

1 Comment

AttributeError: 'dict' object has no attribute 'read' is the error I get with Django 2.2.11 with Python 3.7.2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.