'Iterate Python dict convert Mongo ObjectId into string if value is ObjectId

This my Dict structure, I cannot iterate entire dict to find ObjectId as value My Input data:

 {
"_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"
        }
    ]

}

I have tried :

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

But this it doesnt work properly. I need recursive function to convert all ObjectID values into str

Expected 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"
        }
    ]

}



Solution 1:[1]

Never too late, hope this helps someone...

from bson import ObjectId

# convert recursively all ObjectIds to strings in a dictionary
def obj_to_str(data):
    if isinstance(data, dict):
        return {obj_to_str(key): obj_to_str(value) for key, value in data.items()}
    elif isinstance(data, list):
        return [obj_to_str(element) for element in data]
    elif isinstance(data, ObjectId):
        return str(data)
    else:
        return data

Solution 2:[2]

you can try this:

...
from bson import ObjectId

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eyal
Solution 2 Henry John