如何使对象JSON可序列化

时间:2014-10-02 16:37:23

标签: python django serialization django-models

我有一个名为Exercise的对象,它有很多变量,我只希望为每个id序列化两个变量:nameExercise

这就是我的vars的样子:

{'exercises': [<Exercise: 16>, <Exercise: 1>, <Exercise: 177>, <Exercise: 163>, <Exercise: 291>, <Exercise: 209>], 'score': 16.0}

我如何将其变成:

{'exercises': [{16,"some name"}, {1,"some name"}, {177,"some name"}, {163,"some name"}, {291,"some name"}, {209,"some name"}], 'score': 16.0}

当我执行json_dumps(vars(exerciseobject))时,我显然会收到错误TypeError: <Exercise: 16> is not JSON serializable

来源:

# Model
class Exercise(models.Model):
    name = models.CharField(null=False,max_length=255)

    def __unicode__(self):
         return str(self.id)

# Object
class ExercisesObject:
    def __init__(self, aScore, aExercises):
        self.score = aScore
        self.exercises = aExercises # Contains an array of Exercise instances.

# Example:
firstExercise = Exercise.objects.get(pk=1)
secondExercise = Exercise.objects.get(pk=5)
aList = [firstExercise,secondExercise]
obj = ExercisesObject(23,aList)

2 个答案:

答案 0 :(得分:1)

您可以提供自定义json编码器,它是json.JSONEncoder的子类:

class Exercise:
    def __init__(self, value):
        self.value = value
        self.name = 'soem name'


import json
class CustomEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, Exercise):
            return {'value': o.value, 'name': o.name}
        return super(CustomEncoder, self).default(o)

obj = {
    'exercises': [
        Exercise(16),
        Exercise(1),
        Exercise(177),
        Exercise(163),
        Exercise(291),
        Exercise(209)
    ],
    'score': 16.0
}
print(json.dumps(obj, cls=CustomEncoder, indent=4))

输出:

{
    "exercises": [
        {
            "name": "some name",
            "value": 16
        },
        ...
    ],
    "score": 16.0
}

答案 1 :(得分:1)

更简单的方法是使用Django中的serialization本机。

from django.core import serializers


class Exercise(models.Model):
    name = models.CharField(null=False,max_length=255)

    def __unicode__(self):
        return str(self.id)

serialized_data = serializers.serialize("json", Exercise.objects.all(), fields=('name'))

使您的自定义类返回JSON

from json import dumps

class ExercisesObject:
    def __init__(self, aScore, aExercises):
        self.score = aScore
        self.exercises = [{e.id: e.name} for e in aExercises]

    def json(self):
        return dumps({'score': self.score, 'exercises': self.exercises})