Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mxGraph convert JSON data to graph

I have a set of JSON format data which needs to be converted into a mxGraph diagram.

here's how it should look like:

enter image description here

This is the structure of my JSON data

[
  {
    name: 'Globals',    
    parentObjects: []
  },

  {
    name: 'Customer',
    included: true,    
    parentObjects: [
      {
        name: 'Globals',
      }
    ],
  },

  {
    name: 'Product',
    included: true,    
    parentObjects: [
      {
        name: 'Globals',
      }
    ],
  },

  {
    name: 'Transaction',
    included: true,    
    parentObjects: [
      {
        name: 'Customer',
      },
      {
        name: 'Product',
      }
    ],
  },
]

I am very new to mxGraph and I do not have much experience with it so any help would be much appreciated. Thank you.

like image 955
Prajwal Avatar asked Sep 26 '17 11:09

Prajwal


1 Answers

I am also new to mxGraph and wanted a little learning session. So I tried it with your requirements.

I have created a fiddle from the example projects of mxGraph-js.

Here is the primary code that makes the magic:

var root = undefined;

...

var dict = {};
// run through each element in json
data.forEach(function (element) {
    var name = element.name;
    // create graph element
    var graphElement = graph.insertVertex(parent, null, name, 20, 20, 80, 30);
    // check if any parent element
    if (element.parentObjects.length > 0) {
        // run through each parent element
        element.parentObjects.forEach(function (parentObj) {
            var parentGraphElement = dict[parentObj.name];
            // add line between current element and parent
            graph.insertEdge(parent, null, '', parentGraphElement, graphElement);          
        });
    } else {
        // set root for layouting
        root = graphElement;
    }
    // add element to dictionary. this is needed to find object later(parent)
    dict[name] = graphElement;
});

...

// Creates a layout algorithm to be used with the graph
var layout = new mxHierarchicalLayout(graph, mxConstants.DIRECTION_NORTH);

// Moves stuff wider apart than usual
layout.forceConstant = 140;
if (root) {
    layout.execute(parent, root);
}

Happy Coding, Kalasch

like image 61
Kalaschni Avatar answered Oct 13 '22 22:10

Kalaschni