简体   繁体   中英

Dynamic creation of JSON using JavaScript

I want to create a JSON of the following format dynamically using JavaScript. I have tried to do this, but it is so nested I am getting errors all the time. Could you please help me with this?

    {
     "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}
      ]
      }
     ]
    }
   ]}

It is a part of the same structure, and itself repeats over again and again. Please help me with this.

Something like this?

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]));
});​

At last print json JSON.stringify(output)

Following function can be used to create each node

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

Now creating tree dynamically is easier

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

You can add children to each node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM