mxGraph convert JSON data to graph
Asked Answered
A

1

5

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.

Ataractic answered 26/9, 2017 at 11:7 Comment(0)
D
6

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

Duress answered 2/10, 2017 at 12:53 Comment(2)
Works perfectly! Thank youAtaractic
I need 15 reputation to do that. I will surely mark it as accepted once I have my reputation increased.Ataractic

© 2022 - 2024 — McMap. All rights reserved.