【问题标题】:How to serialize a list of dictionaries into json and return the response?如何将字典列表序列化为 json 并返回响应?
【发布时间】:2019-07-01 05:42:55
【问题描述】:
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 可序列化的”

【问题讨论】:

  • 你能分享你正在使用的json和抛出这个错误的代码吗?
  • response_list =[{'_id': ObjectId('5c5ac3227e23080a2beac8a5'), 'date': datetime.datetime(2019, 2, 3, 0, 0), 'per_service_bill': {'Network' : 5.234823, '存储': 0.00355492071}, 'total_cost': 5.23837792071}, {'_id': ObjectId('5c5ac32d7e23080a2beac8be'), 'date': datetime.datetime(2019, 2, 4, 0, 0),'per_service_bill ':{'网络':4.9254925499999995,'存储':0.00351209034},'total_cost':4.92900464034}]
  • 您需要展示更多您正在尝试的代码。因为从错误消息看来,您正在尝试序列化 TypeError 的对象而不是列表
  • 你能分享你的相关views吗?我也尝试了你的 json 数据并且没有返回错误 return Response(response_list, status=status.HTTP_200_OK)
  • @uedemir 这是我尝试的第一件事,但也没有用

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


【解决方案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
  }
]

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

【讨论】:

  • 我会将“_id”作为字符串存储在数据库本身中,但不能将“日期”存储为字符串。如果我这样做,我将无法执行我在这里执行的查询:db.MyCollection.find({"date": {'$gte': from_date, '$lte': to_date}}):跨度>
  • 我猜 ObjectId 是一个整数,因此您可能希望在返回字典之前将其转换为整数。我想这里的困难是你试图从数据库查询中返回一个 json。
猜你喜欢
  • 1970-01-01
  • 2020-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
  • 2020-09-23
  • 2019-10-05
  • 1970-01-01
相关资源
最近更新 更多