在Python中,获取JSON或字典中的所有键路径组合可以通过递归函数来实现。以下是一个示例代码,展示了如何获取所有键路径组合:
def get_key_paths(data, current_path=None, all_paths=None):
if current_path is None:
current_path = []
if all_paths is None:
all_paths = []
if isinstance(data, dict):
for key, value in data.items():
new_path = current_path + [key]
all_paths.append(new_path)
get_key_paths(value, new_path, all_paths)
elif isinstance(data, list):
for index, item in enumerate(data):
new_path = current_path + [index]
all_paths.append(new_path)
get_key_paths(item, new_path, all_paths)
return all_paths
# 示例JSON数据
example_json = {
"a": 1,
"b": {
"c": 2,
"d": [3, 4, {"e": 5}]
},
"f": [6, {"g": 7, "h": {"i": 8}}]
}
# 获取所有键路径组合
paths = get_key_paths(example_json)
for path in paths:
print(" -> ".join(map(str, path)))
['a']
, ['b', 'c']
。['b', 'd', 0]
。def get_key_paths(data, current_path=None, all_paths=None, visited=None):
if current_path is None:
current_path = []
if all_paths is None:
all_paths = []
if visited is None:
visited = set()
data_id = id(data)
if data_id in visited:
return all_paths
visited.add(data_id)
# 其余代码与之前相同...
通过上述方法和注意事项,可以有效地获取和处理JSON或字典中的所有键路径组合。
领取专属 10元无门槛券
手把手带您无忧上云