如何在D3.js中处理用户定义的json格式

问题描述:

我有一个格式为json的文件。我想用d3.js如何在D3.js中处理用户定义的json格式

"x": 
    { 
     "a": 
     { 
       no.of employees:30 
       total salary:2500000 
       count_email:25 
     } 
     "b": 
     { 
       no.of employees:20 
       total salary:350000 
       count_email:25 

      } 
    } 

    "y": 
    { 

     "c": 
     { 
       no.of employees:30 
       total salary:4500000 
       count_email:30 

      } 
     } 
    "z": 
    { 
     "d": 
     { 
       no.of employees:40 
       total salary:550000 
       count_email:40 
     } 
     "e": 
     { 
       no.of employees:10 
       total salary:100000 
       count_email:15 

     } 
     "f": 
     { 
       no.of employees:15 
       total salary:1500000 
       count_email:15 

     } 
    } 

如何访问每个分支机构和支行进行处理访问此文件的每个分支和支行。如何知道这个json格式的密钥

您的Json格式错误: 在此之前,请使用JsonLint.com等工具对其进行验证。 它应该是这个样子的是:

data = { 
"x": [{ 
    "a": { 
     "ff": 30, 
     "fff": 2500000, 
     "fff": 25 
    }, 
    "b": { 
     "ff": 30, 
     "fff": 2500000, 
     "fff": 25 
    } 
}], 
"y": [{ 
    "a": { 
     "ff": 30, 
     "fff": 2500000, 
     "fff": 25 
    }, 
    "b": { 
     "ff": 30, 
     "fff": 2500000, 
     "fff": 25 
    } 
}] 


}; 

你可以循环到你的对象这样的:

Employee = []; 
for (x in data) { 
// Access to the first level 
    for (y in x) { 
    //Access to the second level 

    console.log(data[x][y]); 
    // Here you could store each of your object into a new tab that you could use in d3.js 
    Employee.push(data[x][y]); 
    } 
} 

没什么特别的D3做到这一点。

您可以使用简单的javascript来处理这种情况。

事情是这样的:

d3.json("my.json", function(error, json) { //load json using d3 
    if (error) return console.warn(error); 
    var keys = Object.keys(json); //get all the keys 
    console.log(keys, "Branch") //print on console 
    keys.forEach(function(key){ 
    var subBranch = Object.keys(json[key]); //get all subbranch for key 
    console.log(subBranch, "SubBranch of " + key); //print subbranch and key 
    }) 
}); 

会产生输出这样的:

["x", "y", "z"] "Branch" 
["a", "b"] "SubBranch of x" 
["c"] "SubBranch of y" 
["d", "e", "f"] "SubBranch of z" 

工作代码here

+0

它显示类型错误:无法转换未定义反对 demd3。 html:10 d3.json/

+0

对不起,我没有得到你在这里做什么..谁显示_TypeError:can 't将undefined转换为object_我的plunk按预期工作检查控制台.. – Cyril

+0

我认为您正面临错误,因为您的JSON格式不正确,请检查我的plunk是否有正确的格式。 – Cyril