python - 如何将扁平化的数据转换为结构化的 json?
问题描述
这是主要的展平元素,也就是输入数据:
['a-ab-aba-abaa-abaaa', 'a-ab-aba-abab', 'a-ac-aca-acaa', 'a-ac-aca-acab']
这是我需要的目标数据,也就是输出数据:
[
{
"title": "a",
"children": [
{
"title": "ab",
"children": [
{
"title": "aba",
"children": [
{
"title": "abaa",
"children": [
{
"title": "abaaa"
}
]
},
{
"title": "abab"
}
]
}
]
},
{
"title": "ac",
"children": [
{
"title": "aca",
"children": [
{
"title": "acaa"
},
{
"title": "acab"
}
]
}
]
}
]
}
]
我以为我可以使用deep-for-loop迭代来生成这个json数据,但是太难了,因为level的数量会大于10。所以我认为for-loop在这个过程中不能做,有没有什么算法或使用一个打包的代码来实现一个功能来实现这个目标?如果你能分享你的心态,我很感激,上帝保佑你!
解决方案
这是使用 itertools 的递归解决方案。我不知道这是否足以满足您的目的,但它确实有效。它的工作原理是将您的字符串列表转换为列表列表,然后将其划分为具有相同第一个键的列表,然后构建字典并在删除第一个键的情况下重复。
from itertools import groupby
from pprint import pprint
data = ['a-ab-aba-abaa-abaaa', 'a-ab-aba-abab', 'a-ac-aca-acaa', 'a-ac-aca-acab']
components = [x.split("-") for x in data]
def build_dict(component_list):
key = lambda x: x[0]
component_list = sorted(component_list, key=key)
# divide into lists with the same fist key
sublists = groupby(component_list, key)
result = []
for name, values in sublists:
value = {}
value["title"] = name
value["children"] = build_dict([x[1:] for x in values if x[1:]])
result.append(value)
return result
pprint(build_dict(components))
输出:
[{'children': [{'children': [{'children': [{'children': [{'children': [],
'title': 'abaaa'}],
'title': 'abaa'},
{'children': [], 'title': 'abab'}],
'title': 'aba'}],
'title': 'ab'},
{'children': [{'children': [{'children': [], 'title': 'acaa'},
{'children': [], 'title': 'acab'}],
'title': 'aca'}],
'title': 'ac'}],
'title': 'a'}]
要将此 dict 转换为 json,您可以使用json.dumps
json 模块。我希望我的解释清楚。
推荐阅读
- android - 使用 Android 导航组件创建回栈
- go - 将 Caddy 导入 go 项目在依赖项上失败
- javascript - 如何从 HTML 中的用户输入中查找列表的平均值、最大值和最小值
- css - 分割颜色 SVG 线
- python - 适当的条件循环
- python - Python 使用字符串格式运算符打印两个列表
- java - 如何发现列表中缺少的渐进式算术数
在 Java 8 中? - java - Netbeans 8.2 和 JDK 8 中的“无法在文件夹中创建文件夹 s37”
- java - 登录时用户帐户被锁定
- reactjs - 渲染 ReactJS - './images/0.jpg' 有效.. 但 property.image 没有?