2017-09-26 282 views
1

我有一組需要轉換爲mxGraph圖表的JSON格式數據。mxGraph將JSON數據轉換爲圖形

這裏是它看起來應該像:

enter image description here

這是我的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,我沒有與它太多的經驗所以任何幫助將不勝感激。謝謝。

回答

1

我也是mxGraph的新手,想要一點學習課。所以我嘗試了你的要求。

我從example projects of mxGraph-js創建了fiddle

這裏是主要的代碼,使魔:

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

+0

完美的作品!謝謝 –

+0

很高興聽到,請將我的答案標記爲「接受的答案」。 :-) – Kalaschni

+0

我需要15點聲望才能做到這一點。一旦我的聲望提高,我一定會將其標記爲已接受。 –