将CSV文件转换为JSON,以获取创建D3分类树的树类似结构



我有一个格式的CSV文件:

"","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文件中代表的"社交"代表以前的孩子,路径被添加到最后一个节点。

我试图将一个阵列中的社交事物分开为

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

然后使用此X分析json。

我只为第一行(不是CSV的头)做到的,就像您的结果示例一样,我认为它可以做您想要的。

因此,您只需制作一系列物品,然后通过parseitem将其传递。注意:您的最终结果不是对象,而是一个数组。

这不是真正需要的,但是我使其成为递归功能

所有.innerhtml ...只是为了展示什么。如果您愿意,请删除这些行。

您可以从这里拿走它,对吗?

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

最新更新