如何使对象JSON serializab

2024-10-02 18:22:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我的VAR是这样的:

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

如何将其转化为:

^{pr2}$

当我做一个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)

Tags: selfidgetmodelobjectsmodelsdefclass
2条回答

更简单的方法是使用来自Django的serializationnative。在

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

^{pr2}$

您可以提供自定义json编码器,它是^{}的子类:

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))

输出:

^{pr2}$

相关问题 更多 >