[英]How to build recursive JSON hierarchy tree?
我想做 json 樹,里面有多個父級,你會在 child_id 列中看到我的示例 dataframe,要成為父級的行必須等於 0,它將是 Color 和 Mobile,每個子級將 id 綁定到父級。
我的資料
import pandas as pd
data = {
'id': ['2', '13', '14', '15', '16', '17', '18'],
'name': ['color', 'red', 'blue', 'ruby red', 'mobile', 'iphone', 'sumsung'],
'child_id': ['0', '2', '2', '13', '0', '16', '16']
}
df = pd.DataFrame(data)
df
預計 Output
[
{
'name': 'color',
'id': 2,
'child_id': 0,
'children': [
{
'name': 'red',
'id': 13,
'child_id': 2,
'children': [
{
'name': 'ruby red',
'id': 15,
'child_id': 13,
},
],
},
{
'name': 'blue',
'id': 14,
'child_id': 2,
},
],
},
{
'name': 'mobile',
'id': 16,
'child_id': 0,
'children': [
{
'name': 'iphone',
'id': 17,
'child_id': 16,
},
{
'name': 'samsung',
'id': 18,
'child_id': 16,
},
],
},
]
您可以在沒有 pandas 的情況下執行此操作。只需迭代初始數據以創建字典,以id
為鍵,並將相應的對象(字典)作為值。
然后再次迭代數據以將這些對象鏈接到它們的父對象。
這是如何完成的:
def makehiearchy(data):
result = []
d = { "0": { "children": result } }
for id, name, child_id in zip(data["id"], data["name"], data["child_id"]):
d[id] = { "name": name, "id": id, "child_id": child_id }
for id, child_id in zip(data["id"], data["child_id"]):
parent = d[child_id]
if "children" not in parent:
parent["children"] = []
parent["children"].append(d[id])
return result
# Example run
data = {
'id': ['2', '13', '14', '15', '16', '17', '18'],
'name': ['color', 'red', 'blue', 'ruby red', 'mobile', 'iphone', 'sumsung'],
'child_id': ['0', '2', '2', '13', '0', '16', '16']
}
hierarchy = makehiearchy(data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.