2014-10-02 3 views
0

У меня есть объект с именем Exercise, который имеет много переменных, и я хочу только сериализовать две переменные: id и name для каждого Exercise.Как сделать объект JSON serializable

Это как мои вары выглядит следующим образом:

{'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) 
+0

Какие рамки/ОРМ вы используете? –

+0

@MauroBaraldi, я использую Django ORM. – JavaCake

+0

Итак, возможно, [это] (https://docs.djangoproject.com/en/dev/topics/serialization/) может вам помочь. –

ответ

1

Чем проще способ сделать это с помощью 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}) 
+0

Этот пример не сериализует список 'упражнений' в' ExercisesObject', который содержит объекты 'Exercise'. – JavaCake

+0

Обновить вопрос с примерами данных 'aScore' и' aExercises'. И откуда взялись эти данные? –

+0

Я добавил минимальный пример. – JavaCake

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

Я получаю следующую ошибку: 'TypeError: <__ main __. Obj instance at 0x23e6cb0> не JSON serializable'. Если я изменю его на 'print json.dumps (obj.exercises, cls = CustomEncoder, sort_keys = True, indent = 4)' он работает, хотя я не получу 'счет' распечатаны, как предполагалось. Как я упоминал ранее, я забыл сказать его Django ORM, но я использую его для utlility, что означает, что я строю объект с элементами, полученными Django-ORM. – JavaCake

Смежные вопросы