1

json.dumps(o) converts a native python object to json
o.to_json() converts a mongoengine object such as Document to json

How do you convert a mixed object?
e.g a python dict, with mongoengine objects as its values?

Are there tools for this? Or should I create a custom JSONEncoder class?

If I do override the encoder, could I create a decoder that reconstructs also the mongoengine objects?

1 Answer 1

1

The following encoder serializes python\mongoengine object mixes

import json
from mongoengine.base import BaseDocument

class MongoengineObjectsJsonEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, BaseDocument):
            return o._data
        elif isinstance(o, datetime):
            return o.isoformat()
        else:
            return json.JSONEncoder.default(self, o)

Notes:

  • This encoder does not add any signature regarding where the python objects end and mongoengine objects begin, so it can't be automatically deserialized correctly to python\mongoengine objects, but rather it will deserialize to a single python object
  • I've also added datetime object serialization to ISO 8601 format
Sign up to request clarification or add additional context in comments.

5 Comments

That won't work, the default json encoder cant handle mongo's data types correctly as bson is a supertype of json. MongoEngine just uses pymongo (see bson.json_utils) for the encoding of individual objects or querysets so you should use that for documents eg: return json_utils.dumps(o.to_mongo())
@Ross - do you mean instead of the specific line return o._data?
@Ross - Assuming yes on the above comment, AFAIK if default() returns a str instead of a dict then later in the decoding the entire object will remain as a string, so maybe you mean return o.to_mongo()
@Ross ping on my questions above :)
i solved my problem by from bson.json_util import dumps and in the end return dumps(o)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.