如何加载json文件并使用fetch函数,以及如何创建网络图表?

时间:2016-03-22 08:07:40

标签: javascript json vis.js

我无法加载JSON文件。通过加载JSON文件,我将能够创建网络图表。我正在使用vis.js http://visjs.org/docs/network/#importGephi库来创建网络图表。

这是我的javascript文件:

    var json = loadJSON("data.json");
    function drawNetwork(json) {
    var parseOptions = {
    edges: { inheritColors: false},
    nodes: {fixed: true, parseColor: false}
    }
    var parsed = vis.network.convertGephi(json, parseOptions);
    var data = {
     nodes: parsed.nodes,
     edged: parsed.edges
    };
      // create a network
      var container = document.getElementById('mynetwork');
      // initialize your network!
      var network = new vis.Network(container, data);
    }
        fetch('data.json')    // here i am using fetch() 
        .then(function(response) {
            return response.json();
         }).then(function(json) {
           drawNetwork(json);
         }).catch(function(err){
         console.log('Fetch error : -S',err);
    });

这是我的JSON文件:data.json

{ "nodes": [
    {"id":"a", "label":"a"},
    {"id":"b", "label":"b"},
    {"id":"c", "label":"c"}
    {"id":"d", "label":"d"},
    {"id":"e", "label":"e"},
    {"id":"f", "label":"f"}
    ],
"edges": [
    {"source":"a", "target":"b"},
    {"source":"b", "target":"d"},
    {"source":"a", "target":"c"},
    {"source":"c","target":"d"},
    {"source":"d","target":"e"},
    {"source":"e","target":"a"},
    {"source":"f","target":"c"}
    ]
}

1 个答案:

答案 0 :(得分:0)

方法convertGephi不存在:

var parsed = vis.network.convertGephi(json, parseOptions);

你可能是指parseGephi?

var parsed = vis.network.parseGephi(json, parseOptions);

另见一个工作示例:

http://visjs.org/examples/network/data/importingFromGephi.html