i具有可以深入嵌套如下的数据结构:
{
'field1' : 'id1',
'field2':{'f1':'id1', 'f2':'id2', 'f3':'id3'},
'field3':['id1','id2', 'id3' ,' id4'],
'field4':[{'f1': 'id3', 'f2': 'id4'}, ...]
.....
}
等等..嵌套可以处于任何深度,并且可以是任何数据结构的排列和组合。
此处ID1,ID2,ID3是使用BSON库生成的objectID的字符串,并通过从MongoDB查询查询记录。我想替换这些ID的所有事件,即;ID1,ID2 ...带有新创建的。
替换必须使ID1在所有位置在所有位置的新ID替换为相同创建的ID,并且对其他ID的相同保留。
对上述内容说明:如果ID5是新生成的ID,则ID5必须在ID1发生等的所有位置发生。
这是我的解决方案:
import re
from bson import ObjectId
from collections import defaultdict
import datetime
class MutableString(object):
'''
class that represents a mutable string
'''
def __init__(self, data):
self.data = list(data)
def __repr__(self):
return "".join(self.data)
def __setitem__(self, index, value):
self.data[index] = value
def __getitem__(self, index):
if type(index) == slice:
return "".join(self.data[index])
return self.data[index]
def __delitem__(self, index):
del self.data[index]
def __add__(self, other):
self.data.extend(list(other))
def __len__(self):
return len(self.data)
def get_object_id_position_mapping(string):
'''
obtains the mapping of start and end positions of object ids in the record from DB
:param string: string representation of record from DB
:return: mapping of start and end positions of object ids in record from DB (dict)
'''
object_id_pattern = r'[0-9a-f]{24}'
mapping = defaultdict(list)
for match in re.finditer(object_id_pattern, string):
start = match.start()
end = match.end()
mapping[string[start:end]].append((start,end))
return mapping
def replace_with_new_object_ids(mapping, string):
'''
replaces the old object ids in record with new ones
:param mapping: mapping of start and end positions of object ids in record from DB (dict)
:param string: string representation of record from DB
:return:
'''
mutable_string = MutableString(string)
for indexes in mapping.values():
new_object_id = str(ObjectId())
for index in indexes:
start,end = index
mutable_string[start:end] = new_object_id
return eval(str(mutable_string))
def create_new(record):
'''
create a new record with replaced object ids
:param record: record from DB
:return: new record (dict)
'''
string = str(record)
mapping = get_object_id_position_mapping(string)
new_record = replace_with_new_object_ids(mapping, string)
return new_record
简而言之,我将字典转换为字符串,然后更换ID并完成了工作。 ,但我觉得这绝对不是这样做的最佳方法,因为如果我没有合适的导入(在这种情况下为DateTime),则可能会失败,而且我可能没有对象类型的信息(这样作为DateTime等。)事先在DB中。 我什至尝试了此处所述的Nested_lookup方法https://github.com/russellballestrini/nested-lookup/blob/master/nested_lookup/nested_lookup.pyp.py ,但不能完全按照我想要的方式工作。有一个更好的方法吗? 注意:效率对我而言并不关心。我想要的是用新ID自动化这些ID的过程,以节省时间手动进行。 编辑1:我将以从mongodb获得的记录来调用create_new()作为参数 编辑2:结构可以具有其他对象,例如DateTime作为值 例如: 其他对象必须不受影响,只有ID必须替换 {
'field1' : 'id1',
'field2':{'f1':datetime.datetime(2017, 11, 1, 0, 0), 'f2':'id2', 'f3':'id3'},
'field3':['id1','id2', 'id3' ,' id4'],
'field4':[{'f1': 'id3', 'f2': datetime.datetime(2017,11, 1, 0 , 0)}, ...]
.....
}
您可以使用递归函数向下钻入嵌套在输入数据结构中的字符串。
def replace_ids(obj, new_ids=None):
if new_ids is None:
new_ids = {}
if isinstance(obj, dict):
return {key: replace_ids(value, new_ids) for key, value in obj.items()}
if isinstance(obj, list):
return [replace_ids(item, new_ids) for item in obj]
if isinstance(obj, str):
if obj not in new_ids:
new_ids[obj] = generate_new_id()
return new_ids[obj]
return obj
generate_new_id
是一个应确定要生成新ID的函数。
借助 MichaelRccurtis 答案我可以做以下操作:
from bson import ObjectId
import datetime
def replace_ids(obj, new_ids=None):
if new_ids is None:
new_ids = {}
if isinstance(obj, dict):
return {key: replace_ids(value, new_ids) for key, value in obj.items()}
if isinstance(obj, list):
return [replace_ids(item, new_ids) for item in obj]
if isinstance(obj, str):
if obj not in new_ids:
new_ids[obj] = generate_new_id(obj)
return new_ids[obj]
if isinstance(obj, ObjectId):
return ObjectId()
return obj
def generate_new_id(obj):
if is_valid_objectid(obj):
return str(ObjectId())
return obj
def is_valid_objectid(objid):
if not objid:
return False
obj = ObjectId()
return obj.is_valid(objid)
a = {'_id':ObjectId('5a37844dcf2391c87fb4f845'),
'a':'5a37844dcf2391c87fb4f844',
'b':[{'a':'5a37844dcf2391c87fb4f844', 'b':'ABCDEFGH'},{'a':'5a37844dcf2391c87fb4f846', 'b':'abc123456789111111'}],
'c':['5a37844dcf2391c87fb4f846','5a37844dcf2391c87fb4f844','5a37844dcf2391c87fb4f847'],
'd':datetime.datetime(2017,11,1,0,0)
}
b = replace_ids(a)
print(b)
输出:
{ '_id': ObjectId('5a380a08147e37122d1ee7de'),
'a': '5a380a08147e37122d1ee7e2',
'c': ['5a380a08147e37122d1ee7e0', '5a380a08147e37122d1ee7e2',
'5a380a08147e37122d1ee7e4'],
'b': [{'b': 'ABCDEFGH', 'a': '5a380a08147e37122d1ee7e2'}, {'b':
'abc123456789111111', 'a': '5a380a08147e37122d1ee7e0'}],
'd': datetime.datetime(2017, 11, 1, 0, 0)
}
注意:答案可能会根据计算机上的ID生成而有所不同。
向Michaelrccurtis大喊一个了不起的答案