如何在JSON字符串中包含注释?
我有一个视图,它返回一个以JSON格式编码的货物列表...
def get_new_shipments(request):
# ...
shipments = Shipment.objects.filter(filter).exclude(**exclude).order_by(order) \
.annotate(num_bids=Count('bids'), min_bid=Min('bids__amount'), max_bid=Max('bids__amount'))
return json_response(shipments)
def json_response(data):
response = HttpResponse(mimetype='application/json')
serializer = serializers.get_serializer("json")()
data = list(data)
serializer.serialize(data, ensure_ascii=False, stream=response)
return response
但是我在JSON中没有看到那些注释...我该怎么做才能把它们包含进去呢?
1 个回答
1
这看起来是有效的:
return HttpResponse(simplejson.dumps(list(shipments.values()), ensure_ascii=False, default=json_formatter), mimetype='application/json')
def json_formatter(obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()
elif isinstance(obj, Decimal):
return unicode(obj)
else:
raise TypeError, 'Object of type %s with value of %s is not JSON serializable' % (type(obj), repr(obj))