Skip to main content

More human readable JSON serializer/de-serializer for MongoEngine

Build Status Test Coverage Maintainability Documentation Status Image

What This?

This script has MongoEngine Document json serialization more-natural.

Why this invented?

Using MongoEngine to create something (e.g. RESTful API), sometimes you might want to serialize the data from the db into JSON, but some fields are weird and not suitable for frontend/api:

{
  "_id": {
    "$oid": "5700c32a1cbd5856815051ce"
  },
  "name": "Hiroaki Yamamoto",
  "registered_date": {
      "$date": 1459667811724
  }
}

The points are 2 points:

  • _id might not be wanted because jslint disagrees _ character unless declaring jslint nomen:true
  • There are sub-fields such $oid and $date. These fields are known as MongoDB Extended JSON. However, considering MongoEngine is ODM and therefore it has schema-definition methods, the fields shouldn't have the special fields. In particular problems, you might get No such property $oid of undefined error when you handle above generated data on frontend.

To solve the problems, the generated data should be like this:

{
  "id": "5700c32a1cbd5856815051ce",
  "name": "Hiroaki Yamamoto",
  "registered_date": 1459667811724
}

Making above structure can be possible by doing re-mapping, but if we do it on API's controller object, the code might get super-dirty:

"""Dirty code."""
import mongoengine as db


class User(db.Document):
  """User class."""
  name = db.StringField(required=True, unique=True)
  registered_date = db.DateTimeField()


def get_user(self):
  """Get user."""
  models = [
    {
      ("id" if key == "_id" else key): (
        value.pop("$oid") if "$oid" in value and isinstance(value, dict)
        else value.pop("$date") if "$date" in value and isinstance(value, dict)
        else value  #What if there are the special fields in child dict?
      )
      for (key, value) in doc.items()
    } for doc in User.objects(pk=ObjectId("5700c32a1cbd5856815051ce"))
  ]
  return json.dumps(models, indent=2)

To give the solution of this problem, I developed this scirpt. By using this script, you will not need to make the transform like above. i.e.

"""A little-bit clean code."""

import mongoengine as db
import mongoengine_goodjson as gj


class User(gj.Document):
  """User class."""
  name = db.StringField(required=True, unique=True)
  registered_date = db.DateTimeField()


def get_user(self):
  """Get user."""
  return model_cls.objects(
    pk=ObjectId("5700c32a1cbd5856815051ce")
  ).to_json(indent=2)

How to use it

Generally you can define the document as usual, but you might want to inherits mongoengine_goodjson.Document or mongoengine_goodjson.EmbeddedDocument.

Here is the example:

"""Example schema."""

import mongoengine_goodjson as gj
import mongoengine as db


class Address(gj.EmbeddedDocument):
    """Address schema."""

    street = db.StringField()
    city = db.StringField()
    state = db.StringField()


class User(gj.Document):
    """User data schema."""

    name = db.StringField()
    email = db.EmailField()
    address = db.EmbeddedDocumentListField(Address)

More details... there's the doc!

If you want to know more, there's read the doc that you want to read. You can now read the doc with drinking a cup of coffee!!

Contribute

Please read the doc for the detail.

License (MIT License)

See LICENSE.md

Metadata

Release files for mongoengine-goodjson-v2 2.0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mongoengine-goodjson-v2 2.0.2
File Size Uploaded
mongoengine_goodjson_v2-2.0.2.tar.gz 31.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for mongoengine-goodjson-v2 2.0.2
File Interpreter ABI Platform
mongoengine_goodjson_v2-2.0.2-py3-none-any.whl Python 3 none any Details

Total release size: 70.1 kB

Release files / mongoengine_goodjson_v2-2.0.2.tar.gz

Download URL mongoengine_goodjson_v2-2.0.2.tar.gz
Size 31.2 kB
Tags Source
SHA-256 checksum
How to use checksums
b899974ab66efc085d07cdf9f948a4c0b0a09bbcb46711221f7cb5fd9583acdc
BLAKE2b-256 checksum
How to use checksums
9cde9ca76da8f3cb62ae1fe8614d9813d3d58b2a24bd665bb6c25a1d41b78537
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.11.9

Release files / mongoengine_goodjson_v2-2.0.2-py3-none-any.whl

Download URL mongoengine_goodjson_v2-2.0.2-py3-none-any.whl
Size 38.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e6086585355d2375e22f1fbf0a26e82f2f89f15bea2a52a61c3ad06ae69d66d1
BLAKE2b-256 checksum
How to use checksums
d4b3a5c7488c7ba43b268b613fdd3a2ab2e8623addb9b0e823ee97bb48454c94
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.11.9

Release history Release notifications | RSS feed

This release

2.0.2 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page