【发布时间】:2015-06-09 18:59:56
【问题描述】:
我试图从我生成的 .csv 创建一个 JSON 文件(用于 D3),如下所示:
uat,soe1.1,deploy-mash-app40-uat,3.8.2.8,org.cgl.kfs.mas.mashonline,mashonline-ui-static
uat,soe1.1,deploy-mash-app22-uat-has,1.0.1.RC1,org.cgl.kfs.mas.mashonline,realtime_balances_mims_feeder
stg,soe1.1,deploy-coin-app2-stg,1.1.2,org.mbl.coin.ui.visormobile,vm-web-ui
stg,soe1.1,deploy-coin-app2-stg,1.2.14,org.mbl.coin.ui.factfind,factfind-web-ui
尝试了几种方法,包括 StackOverflow 中的几乎所有帖子。 我想要的 D3 JSON 是这样的:
{
"name": "flare",
"children": [
{
"name": "uat",
"children": [
{
"name": "soe1.1",
"children": [
{
"name": "deploy-mash-app40-uat",
"children": [
{
"name": "mashonline-ui-static",
"children": [
{
"name": "com.cgl.bfs.mas.mashonline",
"size": 3938
},
{
"name": "3.8.2.8",
"size": 3812
}
]
}
]
},
{
"name": "deploy-mash-app22-uat-has",
"children": [
{
"name": "realtime_balances_mims_feeder",
"children": [
{
"name": "1.0.1.RC1",
"size": 3534
},
{
"name": "com.cgl.bfs.mas.mashonline",
"size": 5731
}
]
}
]
}
]
}
]
},
{
"name": "stg",
"children": [
{
"name": "soe1.1",
"children": [
{
"name": "deploy-coin-app2-stg",
"children": [
{
"name": "vm-web-ui",
"children": [
{
"name": "1.1.2",
"size": 3812
},
{
"name": "com.mbl.coin.ui.visormobile",
"size": 6714
}
]
},
{
"name": "factfind-web-ui",
"children": [
{
"name": "1.2.14",
"size": 5731
},
{
"name": "com.mbl.coin.ui.factfind",
"size": 7840
}
]
}
]
}
]
}
]
}
]
}
基本上,将最后两列值作为第 4 列的兄弟。 在此先感谢(我也是 python 的新手)。
试过了 Link1 Link2 和许多其他链接,但我无法使其工作
我运行的代码如下(感谢上述链接之一),但我发现在到达单元格时很难添加“名称”、“孩子”节点。
import json
import csv
tree = {}
name = "name"
children = "children"
reader = csv.reader(open("cleaned_new_test.txt", 'rb'))
reader.next()
for row in reader:
print tree
subtree = tree
for i, cell in enumerate(row):
if cell:
if cell not in subtree:
subtree[cell] = {} if i<len(row)-1 else 1
print subtree
subtree = subtree[cell]
print json.dumps(tree, indent=4)
【问题讨论】:
-
D3 也可以读取 csv 文件,如果这有帮助 see here
-
你从哪里得到
size? -
@jedwards 大小只是我随机添加的一个值,只是为了符合 D3 的格式。现在没有任何意义。
-
@RúnarBerg 谢谢,但 D3 似乎没有提供帮助将 csv 格式化为我们自己的自定义格式的 json。
-
你能验证你写的json就是你想要的json——具体来说,输出的后“一半”的结构与第一个不同。
org.mbl.coin.ui.factfind看起来像是重复的。在前半部分,您将第 4 列和第 5 列作为第 6 列的后代。在第三个条目中,将第 4 列和第 6 列作为第 5 列的后代。在最后一个条目中,将第 5 列和第 6 列作为第 5 列的后代.