mxGraph 将 JSON 数据转换为图形

mxGraph convert JSON data to graph

我有一组JSON格式的数据需要转换成mxGraph图

它应该是这样的:

这是我的JSON数据的结构

[
  {
    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',
      }
    ],
  },
]

我是 mxGraph 的新手,没有太多经验,因此非常感谢任何帮助。谢谢。

我也是 mxGraph 的新手,想进行一些学习。所以我按照你的要求试了一下。

我创建了一个fiddle from the example projects of mxGraph-js

这是创造奇迹的主要代码:

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

快乐编码,Kalasch