Skip to main content
 首页 » 编程设计

python之从路径列表转换为 Flare json 格式

2024年12月31日10落叶

我在 python 中有这样的数据:

[['a', 'b', 'c', 50], 
 ['a', 'b', 'd', 100], 
 ['a', 'b', 'e', 67], 
 ['a', 'g', 'c', 12], 
 ['q', 'k', 'c', 11], 
 ['q', 'b', 'p', 11]] 

其中列表的每个元素都是一个完整的层次路径,最后一个元素是路径的大小。要在 D3 中进行可视化,我需要数据采用 flare 数据格式 - 参见此处:

https://github.com/d3/d3-hierarchy/blob/master/test/data/flare.json

所以短片看起来像这样

{ 
 "name": "root", 
 "children": [ 
  { 
   "name": "a", 
   "children": [ 
    { 
     "name": "b", 
     "children": [ 
      {"name": "c", "value": 50}, 
      {"name": "d", "value": 100}, 
      {"name": "e", "value": 67}, 
     ] 
    }, 
    { 
     "name": "g", 
     "children": [ 
      {"name": "c", "value": 12}, 
     ] 
    }, 

等等……

从我一直在查找的内容来看,我认为解决方案是递归的,并且会在 Python 字典上使用 json 库,但我似乎无法让它工作。任何帮助是极大的赞赏。

请您参考如下方法:

这是一个使用递归的解决方案:

 def add_to_flare(n, flare): 
     children = flare["children"] 
 
     if len(n) == 2: 
         children.append({"name": n[0], "value": n[1]}) 
     else: 
         for c in children: 
             if c["name"] == n[0]: 
                 add_to_flare(n[1:], c) 
                 return 
 
         children.append({"name": n[0], "children": []}) 
         add_to_flare(n[1:], children[-1]) 
 
 flare = {"name": "root", "children": []}  
 
 for i in data: 
     add_to_flare(i, flare) 

为了更好地显示它,我们可以使用 json 库:

import json 
print(json.dumps(flare, indent=1)) 
 
{ 
 "name": "root",  
 "children": [ 
  { 
   "name": "a",  
   "children": [ 
    { 
     "name": "b",  
     "children": [ 
      { 
       "name": "c",  
       "value": 50 
      },  
      { 
       "name": "d",  
       "value": 100 
      },  
      { 
       "name": "e",  
       "value": 67 
      } 
     ] 
    },  
    { 
     "name": "g",  
     "children": [ 
      { 
       "name": "c",  
       "value": 12 
      } 
     ] 
    } 
   ] 
  },  
  { 
   "name": "q",  
   "children": [ 
    { 
     "name": "k",  
     "children": [ 
      { 
       "name": "c",  
       "value": 11 
      } 
     ] 
    },  
    { 
     "name": "b",  
     "children": [ 
      { 
       "name": "p",  
       "value": 11 
      } 
     ] 
    } 
   ] 
  } 
 ] 
}