使用JavaScript动态创建JSON

时间:2015-12-06 08:06:55

标签: 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}
      ]
      }
     ]
    }
   ]}

它是同一结构的一部分,本身一再重复。请帮帮我。

2 个答案:

答案 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)

答案 1 :(得分: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})

您可以为每个节点添加子项。