转换常规JSON为flare.json为d3.js?
问题描述:
我有像这样一个JSON:转换常规JSON为flare.json为d3.js?
{
"a": {
"x": {
"y": {
"a": {},
"z": {},
"b": {}
}
},
"c": {},
"b": {
"c": {
"d": {}
}
},
"d": {},
...
}
}
是否有一个快速的方法来将其转换为flare.json格式?
像这样:
{
"name":"a",
"children":[
{
"name":"x",
"children":
{
"name":"y",
"children":[{"name":"a", "size":0},{"name":"z","size":0},{"name":"b","size":0}]
...
}
谢谢。
答
我为此想出了一系列正则表达式转换。
#replace-this #with-this
^\s*" \{"name":"
: \{\}, \},
: \{\} \}
": \{$ ","children":\[
^\s*\}, \]\},
^\s*\} \]\}
#in that order
,只是删除第一个和最后一行(应该是一个额外的{
和]}
)上应用这些正则变换
,
这样的:
{
"a": {
"x": {
"y": {
"a": {},
"z": {},
"b": {}
}
},
"c": {},
"b": {
"c": {
"d": {}
}
},
"d": {}
}
}
会变成这样:
{
"name": "a",
"children": [{
"name": "x",
"children": [{
"name": "y",
"children": [{
"name": "a"
},
{
"name": "z"
},
{
"name": "b"
}]
}]
},
{
"name": "c"
},
{
"name": "b",
"children": [{
"name": "c",
"children": [{
"name": "d"
}]
}]
},
{
"name": "d"
}]
}
然后它可以与一些d3js示例一起使用。
答
你将不得不编写自己的JSON或函数来动态更改JSON。 Flare.json只遵循一个遵循Mike Bostock的d3文件的模式。
我给你一个提示。你写的模式似乎是(在伪代码)
array("name":"a", "children":array("name":"x","children":array(.....
基本上,你需要为了得到想要的结果来创建多维数组。不幸的是,我不知道你是如何得到你的数据的,所以我不能告诉你更多。如果使用PHP使用json_encode方法
echo json_encode($jsonArray)
或在javascript使用,以获得阵列变成JSON json.stringify
var json = JSON.stringify($jsonArray)
。
@Neal我确实想出了一些奇特的东西!看看我的答案! – ComputerFellow 2013-05-13 12:50:38