0

MappedClassオブジェクトをに変換するにはどうすればよいJSONですか?

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

上記のコードでは、MappedClass オブジェクトが JSON シリアライズ可能ではないというエラーが発生します。

MappedClass を JSON に変換するBSON のjson_utilに似たユーティリティはありますか? またはTypeError: ObjectId('') is not JSON serializableに記載されているようにエンコーダーを作成する必要がありますか

Python 2.7を使用しています

4

1 に答える 1

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
于 2014-10-22T15:02:48.510 に答える