如何将字典列表序列化为json并返回响应?

时间:2019-02-07 06:45:29

标签: python json django django-rest-framework django-serializer

class HelloView(ModelViewSet):
  serializer_class = HelloSerializer
  def get(self, request, *args, **kwargs):
    range_type = request.data['range_type'].lower()
    if range_type == "daily":
        try:
            client = MongoClient('localhost', 27017)
            db = client['MyDatabase'] 
            from_date=datetime.datetime.strptime(request.data['from_date'], "%Y-%m-%d")
            to_date = datetime.datetime.strptime(request.data['to_date'], "%Y-%m-%d")
            response_list = []
            for i in db.MyCollection.find({"date": {'$gte': from_date,
                                                              '$lte': to_date}}):
                response_list.append(i)
            return JsonResponse(response_list, safe=False)
        except Exception as e:
            return Response({"status": e}, status=HTTP_400_BAD_REQUEST)

我的词典列表为:

response_list = [
    {
        '_id': ObjectId('5c5ac3227e23080a2beac8a5'),
        'date': datetime.datetime(2019, 2, 3, 0, 0),
        'per_service_bill': {'network': 5.234823, 'storage': 0.00355492071},
        'total_cost': 5.23837792071
    },
    {
        '_id': objectid('5c5ac32d7e23080a2beac8be'),
        'date': datetime.datetime(2019, 2, 4, 0, 0),
        'per_service_bill': {'network': 4.9254925499999995, 'storage': 0.00351209034},
        'total_cost': 4.92900464034
    }
] 

我已经尝试了这些(使用它们各自的进口),但是没有一个起作用:

  1. 返回JsonResponse(response_list,safe = False)
  2. json.dumps(response_list,safe = False)
  3. serializers.serialize('json',response_list)

谁能告诉我们解决办法?

我需要返回json响应,但它给出错误为:

“ TypeError:TypeError类型的对象不可JSON序列化”

1 个答案:

答案 0 :(得分:1)

ObjectId的类型不清楚,而datatime是复杂的类型。 Json专注于序列化字典,列表,整数,浮点数和字符串。此类型列表中未包含的所有内容都无法序列化。我忽略了ObjectId对象,而得到的错误是     Object of type 'datetime' is not JSON serializable

一种解决方案是对变量进行字符串化处理:

response_list = [
  {
    '_id': str(ObjectId('5c5ac3227e23080a2beac8a5')),
    'date': str(datetime.datetime(2019, 2, 3, 0, 0)),
    'per_service_bill': {'network': 5.234823, 'storage': 0.00355492071},
    'total_cost': 5.23837792071
  },
  {
    '_id': str(ObjectId('5c5ac32d7e23080a2beac8be')),
    'date': str(datetime.datetime(2019, 2, 4, 0, 0)),
    'per_service_bill': {'network': 4.9254925499999995, 'storage': 0.00351209034},
    'total_cost': 4.92900464034
  }
]

最后,您将需要复杂对象的字典或字符串表示形式。然后,您可能会从客户端的字符串/字典构建正确的复杂对象。