如果value为ObjectId,则迭代Python dict将Mongo ObjectId转换为字符串

时间:2015-12-17 04:32:59

标签: python mongodb dictionary mongoengine flask-mongoengine

这是我的Dict结构,我不能迭代整个dict来找到ObjectId作为值 我的输入数据:

 {
"_id" : ObjectId("5671947d29c23846797d836a"),
"event_version" : "1.0",
"event_time" : ISODate("2015-12-16T16:42:37.501Z"),
"event_name" : "Create_Assignment",
"user_id" : "admin",
"tenant" : "Demo_Tenant",
"sourceIPAddress" : "",
"user_agent" : "",
"request_parameters" : {
    "username" : "admin",
    "status" : "active",
    "first_name" : "",
    "last_name" : "",
    "is_deleted" : false,
    "updated_by" : "admin",
    "roles" : [ 
        {
            "_ref" : {
                "$ref" : "role",
                "$id" : ObjectId("5671947d29c23846797d8362")
            },
            "_cls" : "Role"
        }, 
        {
            "_ref" : {
                "$ref" : "role",
                "$id" : ObjectId("5671947d29c23846797d8366")
            },
            "_cls" : "Role"
        }
    ]

}

我试过了:

def todict(self, data, obj=None):
    for key in data:
        if isinstance(data[key], (ObjectId)):
            print '>>>>>>>>>>', data[key]
            obj[key]=str(data[key])
        else:
            if not isinstance(data[key], (str, unicode, list, datetime, bool)):
                self.todict(data[key],obj)
            else:
                obj[key]=data[key]
    return obj

但是它不能正常工作。我需要递归函数将所有ObjectID值转换为str

预期的JSON:

 {
"_id" : "5671947d29c23846797d836a",
"event_version" : "1.0",
"event_time" : ISODate("2015-12-16T16:42:37.501Z"),
"event_name" : "Create_Assignment",
"user_id" : "admin",
"tenant" : "Demo_Tenant",
"sourceIPAddress" : "",
"user_agent" : "",
"request_parameters" : {
    "username" : "admin",
    "status" : "active",
    "first_name" : "",
    "last_name" : "",
    "is_deleted" : false,
    "updated_by" : "admin",
    "roles" : [ 
        {
            "_ref" : {
                "$ref" : "role",
                "$id" : "5671947d29c23846797d8362"
            },
            "_cls" : "Role"
        }, 
        {
            "_ref" : {
                "$ref" : "role",
                "$id" : "5671947d29c23846797d8366"
            },
            "_cls" : "Role"
        }
    ]

}

1 个答案:

答案 0 :(得分:-1)

你可以试试这个:

...
from bson import ObjectId

...
def todict(self, data, obj=None):
    for key in data:
        if isinstance(data[key], ObjectId):
            obj[key]=str(data[key])
... ...