ExplodingTiger
ExplodingTiger

Reputation: 367

JSON to model deserialization - custom fields only

I'm developing a Django application which needs to retrieve information from a public API (JSON format). I have the following model:

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    address = models.CharField(max_length=30)

Let's say that the public API I'm using will return information about the first_name and last_name fields, but in addition, it will return a lot more information, like so:

{
"responseInfo": {
    "requestId": "777"
},
"response": {
    "people": [{
        "firstName": "First Name",
        "lastName": "Last Name",
        "coordinates": {
            "address": "Address",
            "email": "[email protected]"
        }
    },
    "firstName": "First Name",
    "lastName": "Last Name",
    "coordinates": {
        "address": "Address",
        "email": "[email protected]"
    },
    {
           ...
    }
  ]
}

}

How can I deserialize only the fields I need? I tried using the Django rest framework serializer, but translating the JSON into my model is never valid since I can't figure out how to omit the fields I don't need.

Upvotes: 0

Views: 72

Answers (1)

Boris Uvarov
Boris Uvarov

Reputation: 68

Maybe just deserialize everything?

deserialized_data = json.loads(data)
for person in deserialized_data['response']['people']:
    # create Person here 
    # (or save values to some data structure to bulk_create later)

Upvotes: 1

Related Questions