1
我想输出一个MongoEngine文档作为JSON对象通过HTTP/Flask发送。我明白我可以简单地这样做:MongoEngine文档JSON输出
doc = VideoRecord.objects.get(id = _id)
return doc.to_json()
但也有一对夫妇与此输出,它看起来像问题:
{"_id": {"$oid": "558021e7b5540f001225c1c6"}, "start": {"$date": 1335205543511}, "end": {"$date": 1398277543511}, "videoref": "http://stuff.com", "sensorid": {"$uuid": "e36fa049a77543c388792544cbe94ab3"}}
首先,我想在ISO格式的日期时间字段,其次我不希望在子对象中使用带$分隔键的嵌套BSON格式。基本上我需要它看起来像:
{
"sensorid": "e36fa049-a775-43c3-8879-2544cbe94ab3",
"start": "2012-04-23T18:25:43.511Z",
"end": "2014-04-23T18:25:43.511Z",
"videoref": "http://stuff.com"
}
我可以看到我可以在文档覆盖to_json,并使用self.to_mongo得到一本字典,但我不知道如何自定义JSON解析和回报我想要的输出风格。任何示例/指针?
编辑:我知道我现在可以使用此代码:
def to_json(self):
rv = '{ "id": "' + str(self.id) + '", "sensorid": "' + str(self.sensorid) + '"'
if self.start is not None:
rv += ', "start": "' + self.start.isoformat() + '"'
if self.end is not None:
rv += ', "end": "' + self.end.isoformat() + '"'
rv += '}'
return rv
但坦率地说,我希望的东西少了几分DIY。仍然..它工作我猜。