0

如何将MappedClass对象转换为JSON

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

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

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

我正在使用 python 2.7

4

1 回答 1

0

到目前为止,我已经创建了一个编码器供我使用。这很hacky,如果有更好的替代品,我会考虑的。

# 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
于 2014-10-22T15:02:48.510 回答