如何在Python

时间:2018-04-20 05:55:25

标签: python json

我有一个像父子关系的数据表。开发了一小块代码来循环遍历所有子节点,如果有子子节点,它会遍历所有子元素 这是代码;

data_df = pd.DataFrame(
    {
        'id':           [1, 2, 3, 4, 5, 6, 7, 8],
        'parent_id':    [0, 0, 1, 1, 3, 3, 3, 4],
        'name': ['assetX', 'assetY', 'assetZ', 'assetQ', 'assetW', 'assetM', 'assetN', 'assetH']
    }
)
def get_children(data_df,parent_id):
    print("parent:"+str(parent_id))
    children_df = data_df.loc[data_df['parent_id'] == parent_id]
    children = children_df['id'].tolist()
    print children
    for child in children:
        print "child:"+str(child)
        get_children(data_df,child)       

parent_id=0
get_children(data_df,parent_id)

我想创建一个类似下面的json;

{
  "assets": [
    {
      "id": "1",
      "name": "assetX",
      "assets": [
        {
          "id": "3",
          "name": "assetZ",
          "assets": [
            {
              "id": "5",
              "name": "assetW",
              "assets": []
            },
            {
              "id": "6",
              "name": "assetM",
              "assets": []
            },
            {
              "id": "7",
              "name": "assetM",
              "assets": []
            }
          ]
        },
        {
          "id": "4",
          "name": "assetQ",
          "assets": [
            {
              "id": "8",
              "name": "assetH",
              "assets": []
            }
          ]
        }
      ]
    },
    {
      "id": "2",
      "name": "assetY",
      "assets": []
    }
  ]
}

同样,主要的挑战是我不知道我会有多少子项目 有什么建议吗?

1 个答案:

答案 0 :(得分:3)

递归是你的朋友

def get_childrens(df, parent_id):
    data = df[df["parent_id"] == parent_id].apply(lambda row: {"id": row["id"],
          "name": row["name"],
          "assets": []}, axis=1)
    data_list = data.tolist() if not data.empty else []
    for i, d in enumerate(data_list):
        d["assets"] = get_childrens(df, d['id'])
    return data_list

然后

import json
print(json.dumps({"assets": get_childrens(df, 0)}, indent=2))

输出符合预期

Output