如何在Python中将路径式键值对转换为嵌套JSON结构?
路径字符串转嵌套结构问题解答
输入数据
/a/b/c/d="value1" /a/b/e/f="value2"
修正后合法目标结构
原目标格式存在JSON语法错误,将b的值改为数组后,合法结构如下:
{ "a": { "b": [ { "c": { "d": "value1" } }, { "e": { "f": "value2" } } ] } }
问题解答
1. Python是否有内置函数完成该转换?
Python没有直接实现这种转换的内置函数。这种将带层级的路径字符串转为特定嵌套结构(尤其是中间节点需要切换为数组的场景)属于自定义业务逻辑,需要手动编写代码处理。
2. 嵌套字典结构a["b"]["c"]["d"]在Python中是否无法实现?
这个判断是错误的,Python完全支持这种多层嵌套的字典结构。例如:
# 定义嵌套字典 a = { "b": { "c": { "d": "value1" } } } # 访问嵌套值 print(a["b"]["c"]["d"]) # 输出: value1
实现转换的示例代码
以下是实现上述转换的Python代码,可处理输入路径并生成修正后的合法嵌套结构:
def parse_paths_to_struct(paths): result = {} for line in paths: # 拆分路径与值部分 path_part, value_part = line.split('=', 1) value = value_part.strip('"') # 拆分路径节点(去除首尾斜杠后按斜杠分割) nodes = path_part.strip('/').split('/') current = result # 遍历路径节点,构建嵌套结构 for i in range(len(nodes)): node = nodes[i] # 当处理到倒数第三个节点时(即b节点),需要将其值设为数组 if i == len(nodes) - 3: if node not in current: current[node] = [] # 构建当前分支的子字典并添加到数组中 sub_dict = {nodes[i+1]: {nodes[i+2]: value}} current[node].append(sub_dict) break # 普通节点构建字典 if node not in current: current[node] = {} current = current[node] return result # 测试输入 input_lines = [ '/a/b/c/d="value1"', '/a/b/e/f="value2"' ] # 生成结构并格式化输出 output_struct = parse_paths_to_struct(input_lines) import json print(json.dumps(output_struct, indent=4))
运行代码后,输出结果与修正后的目标结构一致。
内容的提问来源于stack exchange,提问作者Deepakvg
相关产品推荐
相关产品推荐

