如何在JSON字符串中包含注释? [英] How to include annotation in JSON string?
本文介绍了如何在JSON字符串中包含注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个视图,该视图返回编码为JSON的货运清单...
I've got a view that returns a list of shipments encoded as 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中的那些批注...如何将它们包括在内?
But I don't see those annotations in the JSON anywhere... how do I get them to be included?
推荐答案
这似乎可行:
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))
这篇关于如何在JSON字符串中包含注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文