[英]How to serialize a list of dictionaries into json and return the response?
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
}
]
我已經嘗試了這些(及其各自的進口),但沒有一個工作:
誰能告訴我解決辦法?
我需要返回json響應,但它給出錯誤為:
“ TypeError:TypeError類型的對象不可JSON序列化”
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
}
]
最后,您將需要復雜對象的字典或字符串表示形式。 然后,您可以從客戶端的字符串/字典構建正確的復雜對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.