MongoEngine Document JSON output

2.1k views Asked by At

I would like to output a MongoEngine document as a JSON object to send through HTTP/Flask. I understand I can simply do this:

doc = VideoRecord.objects.get(id = _id)
return doc.to_json()

But there are a couple of problems with this output, which looks like:

{"_id": {"$oid": "558021e7b5540f001225c1c6"}, "start": {"$date": 1335205543511}, "end": {"$date": 1398277543511}, "videoref": "http://stuff.com", "sensorid": {"$uuid": "e36fa049a77543c388792544cbe94ab3"}}

Firstly I want a DateTime field in ISO format, and secondly I don't want this nested BSON format with $ delimited keys in sub-objects. Basically I need it to look like:

{
"sensorid": "e36fa049-a775-43c3-8879-2544cbe94ab3",
"start": "2012-04-23T18:25:43.511Z",
"end": "2014-04-23T18:25:43.511Z",
"videoref": "http://stuff.com"
}

I can see I can override to_json in the Document, and use self.to_mongo to get a dictionary, but I'm not sure how to customise the JSON parsing and return the output style I want. Any examples / pointers?

Edit: I realise I can use this code now:

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

But frankly I was hoping for something a bit less DIY. Still.. it works I guess.

1

There are 1 answers

0
Viacheslav On BEST ANSWER

Instead of concatenating strings you can populate a dictionary and then convert it to json:

import json
...
def to_json(self):
    d = {
           "id": str(self.id),
           "sensorid": str(self.sensorid)
        }
    if not self.start is None:
        d['start'] = self.start.isoformat()
    if not self.end is None:
        d['end'] = self.end.isoformat()

    return json.dumps(d)