明ODM MappedClass json转换

时间:2014-10-21 20:41:01

标签: python ming

如何将MappedClass 对象转换为JSON

json.dumps({"data": mappedClassObject}, indent=True)

上面的代码引发了MappedClass对象不是JSON可序列化的错误。

是否有类似于BSON' json_util的实用程序将MappedClass转换为JSON?或者我是否必须编写TypeError: ObjectId('') is not JSON serializable

中提到的编码器

使用python 2.7

1 个答案:

答案 0 :(得分:0)

截至目前,我已经为我创建了一个编码器。这很糟糕,如果有更好的替代品,我会考虑它。

# MappedClass from Ming is not JSON serializable and we do not have utilities like json_util (for BSON) to convert
# MappedClass object to JSON. Below encoder is created for this requirement.
# Usage: MappedClassJSONEncoder().encode(data)
class MappedClassJSONEncoder(JSONEncoder):
    """
    Returns a MappedClass object JSON representation.
    """

    def _get_document_properties(self, klass):
        """
        Returns the declared properties of the MappedClass's child class which represents Mongo Document
        Includes only the user declared properties such as tenantId, _id etc
        :param klass:
        :return:
        """
        return [k for k in dir(klass) if k not in dir(MappedClass)]

    def _get_attr_json_value(self, attr):
        if isinstance(attr, bson.objectid.ObjectId):
            return str(attr)
        elif isinstance(attr, datetime.datetime):
            return attr.isoformat()
        elif isinstance(attr, dict):
            dict_data = {}
            for member in attr:
                dict_data.update({member: self._get_attr_json_value(attr[member])})
            return dict_data
        else:
            return attr

    def default(self, o):
        mapped_class_attributes = self._get_document_properties(type(o))
        attributes_data = {}
        for attr_name in mapped_class_attributes:
            attr = o.__getattribute__(attr_name)
            attributes_data.update({attr_name: self._get_attr_json_value(attr)})
        return attributes_data