如何将嵌套列表转换为对象

时间:2016-10-17 13:32:41

标签: python django django-rest-framework

当我收到像

这样的JSON数据时
[  
    {  
        "id":1,
        "name":"New Island",
        "residents":[  
            {  
                "name":"Paul",
                "age":"25"
            }
        ]
    },
    {  
        "id":2,
        "name":"One Nation",
        "residents":[  
            {  
                "name":"James",
                "age":"23"
            },
            {  
                "name":"Jessica",
                "age":"26"
            }
        ]
    }
]

drf deserializer使其列出包含OrderedDict

的列表

但是我想把它变成类对象的列表。

这是我的django模型

class Country(models.Model):
    name = models.CharField(max_length=20)

class Resident(models.Model):
    name = models.CharField(max_length=20)
    country = models.ForeignKey('Country', related_name='residents')

2 个答案:

答案 0 :(得分:1)

来自Python的JSON library

import json

data = '[{"id":1,"name":"New Island","residents":[{"name":"Paul","age":"25"}]},{"id":2,"name":"One Nation","residents":[{"name":"James","age":"23"},{"name":"Jessica","age":"26"}]}]'

x = json.loads(data)

for each_set in x:
    for every_person in each_set["residents"]:
        print(every_person["name"]) #getting resident's name
        print(every_person["age"])  #getting age
        print(each_set["name"]) #getting the country name

从那里开始就像将适当的参数传递给像

这样的类一样简单

答案 1 :(得分:0)