2015-12-06 98 views
0

我想使用JavaScript動態創建以下格式的JSON。我試圖做到這一點,但它是如此嵌套,我一直在得到錯誤。你能幫我解決這個問題嗎?使用JavaScript動態創建JSON

{ 
    "name": "flare", 
    "children": [ 
     { 
     "name": "analytics", 
     "children": [ 
     { 
      "name": "cluster", 
      "children": [ 
     {"name": "AgglomerativeCluster", "size": 3938}, 
     {"name": "CommunityStructure", "size": 3812}, 
     {"name": "HierarchicalCluster", "size": 6714}, 
     {"name": "MergeEdge", "size": 743} 
    ] 
    }, 
    { 
    "name": "graph", 
    "children": [ 
     {"name": "BetweennessCentrality", "size": 3534}, 
     {"name": "LinkDistance", "size": 5731}, 
     {"name": "MaxFlowMinCut", "size": 7840}, 
     {"name": "ShortestPaths", "size": 5914}, 
     {"name": "SpanningTree", "size": 3416} 
    ] 
    }, 
    { 
    "name": "optimization", 
    "children": [ 
     {"name": "AspectRatioBanker", "size": 7074} 
     ] 
     } 
    ] 
    } 
    ]} 

它是同一結構的一部分,它本身一遍又一遍地重複。請幫我解決一下這個。

+0

你試過'JSON.parse'嗎? – AdityaParab

+0

你在找這樣的事嗎? http://stackoverflow.com/a/7220510/667599 – Throoze

+0

不,我正在嘗試創建一個上述格式的新兒子。 –

回答

0

像這樣?

var output = []; 
function processJson(parent) { 
    var retVal = { 
     "name": parent.name    
    }; 
    parent.find("children").each(function() { 
     if (!retVal.hasOwnProperty("children")) { 
      retVal.children = []; 
     } 
     retVal.children.push(processJson($(this))); 
    }); 
    return retVal; 
} 


$.each(input, function(i, item) { 
    output.push(processJson(input[i])); 
});​ 

最後打印JSON JSON.stringify(output)

0

以下功能可用於創建每個節點

function Node(obj){ 
$.extend(this,obj); 
this.children = []; 
this.addChild=function(obj){ 
    var temp = new Node(obj); 
    this.children.push(temp); 
    return temp; 
} 
} 

現在創建樹動態更容易

var tree = new Node({}); 
tree 
.addChild({name:'flare'}) 
.addChild({name:'analytics'}) 
.addChild({name:'cluster'}) 
.addChild({name: "AgglomerativeCluster", size: 3938}) 

可孩子增加每個節點。