如何将分层 table 转换为 json

How to convert hierarchical table to json

我正在尝试将多级层次结构 table 转换为我正在创建的视觉对象的特定 JSON 格式。

我在 pandas 数据框中有数据,并尝试按不同级别对其进行分组,但无法使用 pandas 将 groupby 转换为 json。我也尝试过将数据帧转换为 json,但格式不正确。我不确定还需要做什么才能获得我正在寻找的 parent/child 格式。所有 "size" 值只需为 1,这样这部分看起来就足够简单了…… 提前致谢!

**This is what my data looks like**
ColA     ColB     ColC   
Parent1  Child1   
Parent1  Child2   Child2A 
Parent1  Child2   Child2B
Parent1  Child3   Child2A
Parent2  Child1
Parent2  Child2   Child2A

我从 pandas 数据框 to_json 中得到的是逐列创建 json,所以我失去了它的层次结构方面。

所以它:

data = {"Parent1}"{"index #":"col2 value"

我想要的是:

data = ({ "name":"TEST",
"children": [
  {
    "name": "Parent1",
    "children": 
      [
      {
        "name": "Child1",
        "size": "1"
      },
      {
      "name":"Child2",
        "children": 
        [
        {
          "name":"Child2A",
          "size":"1" 
        },
        {
          "name":"Child2B",
          "size":"1" 
        },
        {
          "name":"Child2C",
          "size":"1" 
        },
        {
          "name":"Child2D",
          "size":"1" 
        },
        ],
      },
    {
      "name":"Parent2",
      "children": [
        {
          "name":"Child2A",
          "size":"1" 
        },
        {
          "name":"Child2B",
          "size":"1" 
        },
        {
          "name":"Child2C",
          "size":"1" 
        },
      ]
    },
    ]
  },
  {
    "name": "Parent3",
    "children": 
    [
      {
        "name": "Child1",
        "size": "1",
      },
      {
      "name":"Child2",
      "children": 
      [
        {
          "name":"Child2A",
          "size":"1" 
        },
        {
          "name":"Child2B",
          "size":"1" 
        },
        {
          "name":"Child2C",
          "size":"1" 
        },
      ],
    },
    {
      "name":"Child3",
      "children": 
      [
        {
          "name":"Child3A",
          "size":"1" 
        },
      ],
    },
    ],
  },
]})

我们来了

import json

data = [
    'Parent1  Child1',
    'Parent1  Child2   Child2A',
    'Parent1  Child2   Child2B',
    'Parent1  Child3   Child2A',
    'Parent2  Child1',
    'Parent2  Child2   Child2A',
]

tree = {}

for d in data:
    node = None
    for item in d.split():
        name = item.strip()  # dont need spaces
        current_dict = tree if node is None else node
        node = current_dict.get(name)
        if not node:
            node = {}
            current_dict[name] = node


def walker(src, res):
    for name, value in src.items():
        node = {'name': name, 'size': 1}
        if 'children' not in res:
            res['children'] = []
        res['children'].append(node)
        walker(value, node)

result = {'name': 'TEST'}
walker(tree, result)

print (json.dumps(result, indent = True))