如何将层次表转换为json

时间:2018-12-20 15:26:19

标签: python json hierarchical-data

我正在尝试将多级层次结构表转换为用于创建的视觉效果的特定JSON格式。

我将数据保存在pandas数据框中,并尝试按不同级别对其进行分组,但是随后无法使用pandas将groupby转换为json。我也尝试过仅将数据帧转换为json,但是格式不正确。我不确定要获取我想要的父母/孩子格式还要做什么。所有的“大小”值都只需要为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数据框到_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" 
        },
      ],
    },
    ],
  },
]})

1 个答案:

答案 0 :(得分:0)

我们来了

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))