我有一个可以深层嵌套的数据结构,如下所示:
{
'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并完成了工作。
但我觉得这绝对不是最好的方法,因为如果我没有合适的导入(在这种情况下是日期时间),eval()可能会失败,而且我可能没有对象类型的信息(例如作为日期时间等)预先在DB中。
我甚至尝试了https://github.com/russellballestrini/nested-lookup/blob/master/nested_lookup/nested_lookup.py
中描述的nested_lookup方法但是不能让它以我想要的方式工作。 有一个更好的方法吗?
注意:效率不是我关注的问题。我想要的是自动化用新的id替换这些id的过程,以节省手动操作的时间。
编辑1:我将使用从MongoDB获取的记录作为参数调用create_new()
编辑2:结构可以包含其他对象,例如datetime作为值 例如:
{
'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)}, ...]
.....
}
其他对象必须不受影响,且只能更换ID
答案 0 :(得分:2)
您可以使用递归函数深入查看嵌套在输入数据结构中的字符串。
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的函数。
答案 1 :(得分:0)
在 michaelrccurtis 的帮助下,我可以执行以下操作:
{ '_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)
}
输出:
{{1}}
注意:答案可能因机器上的ID生成而有所不同。
向michaelrccurtis大声喊出一个惊人的答案