我有一个格式的json文件。我想使用d3.js
访问该文件的每个分支和子分支"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格式的键
答案 0 :(得分:0)
您的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]);
}
}
答案 1 :(得分:0)
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