CSV转换为JSON转换

时间:2017-04-26 05:18:51

标签: javascript json function d3.js

我有一个格式为:

的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树层次结构,如下所示:

"Root" : [
    {
        "Sequence" : "Social",
        "children" : [
            {
                "Sequence" : "Social",
                "children" : [
                    {
                        "Sequence" : "Social",
                        "children" : [
                            {
                                "Sequence" : "Social",
                                "children" : [
                                    {
                                        "Sequence" : "Social",
                                        "children" : [
                                            {
                                                "Sequence" : "Social",
                                                "children" : [
                                                    {
                                                        "Sequence" : "Social",
                                                        "children" : [
                                                            {
                                                                "Sequence" : "Social",
                                                                "Path" : 29}],
                                                            }
                                                        }

每个接触点的位置即。 '社会'由 - >表示在每行的CSV文件中表示前一个子节点,并将路径添加到最后一个节点。

我试图将社交内容拆分为一个数组

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

然后使用这个x来解析JSON.Could任何人都可以帮助我。谢谢!

1 个答案:

答案 0 :(得分:1)

您的问题是您在定义对象期间已经调用了匿名函数masterTag。在这种情况下,您分配给masterTag的函数不是adserver的函数,它是一个简单的值赋值。并且在对象创建期间调用该函数时,它的范围不正确,即this不是adserver对象。

,例如,这将有效:

var adserver = {
  createIframe : function (url) {
    console.log(url);
  },
  trackSQ: (function () { })(),
  masterTag: (function (type,cat) {
    var self = this;
    self.createIframe("test");
  })
}

致电

adserver.masterTag("targe0","maste0");

(我已将您的代码更改为最小的示例)