如何更改嵌套有效负载的格式?

时间:2019-03-28 00:59:58

标签: python django

我想从以下位置更改json有效负载:

{
    "grade": "ten",
    "studentdlList": [
        {
            "studentdetail": {
                "name": "mw",
                "rollno": 19
            }
        },
        {
            "studentdetail": {
                "name": "battery",
                "rollno": 44
            }
        }
    ]
}

到下面的表格,因为第一个变得太复杂和多余:

{
    "grade": "ten",
    "studentdlList": [
            "studentdetail": {
                "name": "mw",
                "rollno": 19
            }
        ,
            "studentdetail": {
                "name": "battery",
                "rollno": 44
            }

    ]
}

要获得结果,我的序列化器如下:

class SerializerTemp(serializers.Serializer):
    name =  serializers.CharField()
    rollno =  serializers.IntegerField()

class Studentserializer(serializers.ModelSerializer):
    studentdetail = SerializerTemp(source="*")

    class Meta:
        model = Student
        fields = ('studentdetail',)

class SiteSerializer(serializers.ModelSerializer):
    studentdlList = Studentserializer(many = True)

    class Meta:
        model = Grade
        fields = ("grade", "studentdlList")

最后一个序列化程序也具有update和create(我这里没有提到)。我如何才能将有效载荷更改为指定的格式,从而减少冗余并使其更清晰?

1 个答案:

答案 0 :(得分:1)

正如评论中所说,提供的示例不是有效的JSON。您在此处获得的是对象列表,因此需要使用方括号明确表示该对象:

{
    "grade": "ten",
    "studentdlList": [
        {
            "studentdetail": {
                "name": "mw",
                "rollno": 19
            }
        },
        {
            "studentdetail": {
                "name": "battery",
                "rollno": 44
            }
        }
    ]
}

您可以将代码更改为:

class Studentserializer(serializers.ModelSerializer):  
    class Meta:
        model = Student
        fields = ('name', 'rollno',)

class SiteSerializer(serializers.ModelSerializer):
    studentdlList = Studentserializer(many = True)

    class Meta:
        model = Grade
        fields = ("grade", "studentdlList")

产生类似这样的东西

{
    "grade": "ten",
    "studentdlList": [
        {
            "name": "mw",
            "rollno": 19
        },
        {
            "name": "battery",
            "rollno": 44
        }
    ]
}