2017-08-30 66 views
0

我的格式爲csv文件:轉換一個CSV文件轉換成JSON,從而獲得樹狀結構,創建一個D3分類樹

"","Sequence","Paths","sequence_length" 
"1","Social -> Social -> Social -> Social -> Social -> Social -> Social -> Social",29,8 
"2","Social -> Social -> Social -> Social -> Social -> Social -> Social",30,7 
"3","Social -> Social -> Social -> Social -> Social -> Social",40,6 
"4","Social -> Social -> Social -> Social -> Social",71,5 
"5","Social -> Social -> Social -> Social",156,4 
"6","Social -> Social -> Social",273,3 
"7","Social -> Social -> SEO",40,3 
"8","Social -> Social",729,2 
"9","Social -> SEO -> Social",51,3 
"10","Social -> SEO",180,2 
"11","Social -> SEM",56,2 

我打算將它轉換成JSON樹的層次結構如下:

{ 
"name": "Social", 
"children": [{ 
    "name": "Social", 
    "children": [{ 
     "name": "Social", 
     "children": [{ 
      "name": "Social", 
      "children": [{ 
       "name": "Social", 
       "children": [{ 
        "name": "Social", 
        "children": [{ 
         "name": "Social", 
         "children": [{ 
          "name": "Social", 
          "Path": 29 
         }] 
        }] 
       }] 
      }] 
     }] 
    }] 
}] 
} 

其中每個接觸點即,在每行的CSV文件中用 - >表示的'Social'表示前一個的孩子,並且路徑被添加到最後一個節點。

我試圖在一個陣列中的社會分裂的事情作爲

data.forEach(function(d){ 
var x = d.Sequence.split(' -> '); 

,然後使用這張X解析成JSON.Could請人幫我it.Thanks!

+0

因此,您已經能夠將CSV文件轉換爲對象'數據',這是一個對象數組,每個對象都有'Sequence'屬性,這是一個字符串? – trincot

回答

0

我只做了第一行(而不是csv的頭部),就像你結果的例子,我認爲它是做你想做的。

因此,您只需製作一個項目數組,並通過parseItem傳遞每個項目。注意:你的最終結果不是一個對象,而是一個數組。

它並不真正需要的,但我做了一個遞歸函數

所有.innerHTML ...只是說明wha't回事。如果你願意,刪除這些行。

你可以從這裏拿走吧?

<div id="log"></div> 
<hr/> 
<div id="result"></div> 
<script> 
    var myitem = ["1", "Social -> Social -> Social -> Social -> Social -> Social -> Social -> Social", 29, 8]; 

    function parseItem(item) { 
     // var id = item[0]; 
     var paths = item[1]; 
     var value = item[2]; 
     // var length = item[3]; 
     var splitPath = paths.split(' -> '); 

     var threeDpath = path2tree(splitPath, value); 
     return threeDpath; 

    } 

    // recursive function 
    function path2tree(paths, value) { 
     // for testing and trying to understand what happens 
     document.getElementById('log').innerHTML += JSON.stringify(paths) + '<br/>'; 

     if (paths.length == 1) { // this will only be true the last time 
      return [{ 
       "name": paths[0], 
       "Path": value 
      }]; 
     } else { 
      // splice paths[0], send the rest to the recursive function 
      var path = paths.splice(0, 1); 
      return [{ 
       "name": path[0], 
       "children": path2tree(paths, value) 
      }]; 
     } 
    } 

    window.onload = function() { 
     var threeDpath = parseItem(myitem); 
     document.getElementById('result').innerHTML = JSON.stringify(threeDpath); 
    } 
</script>