首页 > 解决方案 > 如何将扁平化的数据转换为结构化的 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在这个过程中不能做,有没有什么算法或使用一个打包的代码来实现一个功能来实现这个目标?如果你能分享你的心态,我很感激,上帝保佑你!

标签: pythonjsongraphtree

解决方案


这是使用 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.dumpsjson 模块。我希望我的解释清楚。


推荐阅读