Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import json file to create a network in vis.js

Tags:

I am using vis.js to create a mapping, I using file saveAndLoad.html in the example code. The save function is good, I can export json file. But when I load the json file in import function it doesn't create a mapping for me. I don't know what is my misunderstanding please help. this is the import function.

function importNetwork() {
            /*var inputValue = exportArea.value;
            var inputData = JSON.parse(inputValue);

            var data = {
                nodes: getNodeData(inputData),
                edges: getEdgeData(inputData)
            }

            network = new vis.Network(container, data, {});*/

            var gephiJSON = loadJSON("./1.json"); // code in importing_from_gephi.

            // you can customize the result like with these options. These are explained below.
            // These are the default options.
            var parserOptions = {
              edges: {
                inheritColors: false
              },
              nodes: {
                fixed: true,
                parseColor: false
              }
            }

            // parse the gephi file to receive an object
            // containing nodes and edges in vis format.
            var parsed = vis.network.convertGephi(gephiJSON, parserOptions);

            // provide data in the normal fashion
            var data = {
              nodes: parsed.nodes,
              edged: parsed.edges
            };

            // create a network
            var network = new vis.Network(container, data);

            resizeExportArea();
        }
like image 412
Warit Khuntaraporn Avatar asked Mar 10 '17 16:03

Warit Khuntaraporn


1 Answers

I searched quite a bit for a solution to the obstensively simple task of loading an external JSON datafile into a vis.js Network. Here is a working solution.

Read my comments in the HTML file (below), for more information:

  • I installed vis.js via NPM, but you can also just download / source the vis.min.js file;

  • The code provided by visjs.org in the "full options" tab for the Network module edge options was buggy, due to extra commas, etc. I included a working copy in my HTML code (ditto re: the "physics" options).

  • As noted in the comments in my HTML file, the formatting of the JSON datafile is very particular: use double quotation marks; curly braces { } are not quoted (e.g., if you want to define per-edge attributes, in that file); ....

json_test.html

<!doctype html>
<HTML>
<HEAD>
  <meta charset="utf-8" />
  <TITLE>[vis.js] Network | Basic Usage | TEST: Load External JSON Datafile</TITLE>

  <!-- NPM (http://visjs.org/index.html#download_install): -->
  <!-- <script type="text/javascript" src="node_modules/vis/dist/vis.min.js"></script> -->
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>

  <!-- Needed for JSON file import (https://stackoverflow.com/questions/33392557/vis-js-simple-example-edges-do-not-show): -->
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

  <!-- http://visjs.org/index.html#download_install -->
  <!-- <link rel="stylesheet" type="text/css" href="node_modules/vis/dist/vis.css"> -->
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css">

  <style type="text/css">
    #mynetwork {
        /* width: 600px; */
        width: 100%;
        height: 800px;
        border: 2px solid lightgray;
    }
    </style>
</HEAD>

<BODY>

<div id="mynetwork"></div>

<!-- Add an invisible <div> element to the document, to hold the JSON data: -->
<div id="networkJSON-results" class="results" style="display:none"></div>

<script type="text/javascript">

  // -------------------------------------------------------------------------
  // OPTIONS:

  // http://visjs.org/docs/network/#modules
  // http://visjs.org/docs/network/edges.html#
  // http://visjs.org/docs/network/physics.html#

  var options = {
    edges: {
      arrows: {
        to: {enabled: true, scaleFactor:0.75, type:'arrow'},
        // to: {enabled: false, scaleFactor:0.5, type:'bar'},
        middle: {enabled: false, scalefactor:1, type:'arrow'},
        from: {enabled: true, scaleFactor:0.3, type:'arrow'}
        // from: {enabled: false, scaleFactor:0.5, type:'arrow'}
      },
      arrowStrikethrough: true,
      chosen: true,
      color: {
      // color:'#848484',
      color:'red',
      highlight:'#848484',
      hover: '#848484',
      inherit: 'from',
      opacity:1.0
      },
      dashes: false,
      font: {
        color: '#343434',
        size: 14, // px
        face: 'arial',
        background: 'none',
        strokeWidth: 2, // px
        strokeColor: '#ffffff',
        align: 'horizontal',
        multi: false,
        vadjust: 0,
        bold: {
          color: '#343434',
          size: 14, // px
          face: 'arial',
          vadjust: 0,
          mod: 'bold'
        },
        ital: {
          color: '#343434',
          size: 14, // px
          face: 'arial',
          vadjust: 0,
          mod: 'italic'
        },
        boldital: {
          color: '#343434',
          size: 14, // px
          face: 'arial',
          vadjust: 0,
          mod: 'bold italic'
        },
        mono: {
          color: '#343434',
          size: 15, // px
          face: 'courier new',
          vadjust: 2,
          mod: ''
        }
      }
    },
    // http://visjs.org/docs/network/physics.html#
    physics: {
      enabled: true,
      barnesHut: {
        gravitationalConstant: -2000,
        centralGravity: 0.3,
        // springLength: 95,
        springLength: 175,
        springConstant: 0.04,
        damping: 0.09,
        avoidOverlap: 0
      },
      forceAtlas2Based: {
        gravitationalConstant: -50,
        centralGravity: 0.01,
        springConstant: 0.08,
        springLength: 100,
        damping: 0.4,
        avoidOverlap: 0
      },
      repulsion: {
        centralGravity: 0.2,
        springLength: 200,
        springConstant: 0.05,
        nodeDistance: 100,
        damping: 0.09
      },
      hierarchicalRepulsion: {
        centralGravity: 0.0,
        springLength: 100,
        springConstant: 0.01,
        nodeDistance: 120,
        damping: 0.09
      },
      maxVelocity: 50,
      minVelocity: 0.1,
      solver: 'barnesHut',
      stabilization: {
        enabled: true,
        iterations: 1000,
        updateInterval: 100,
        onlyDynamicEdges: false,
        fit: true
      },
      timestep: 0.5,
      adaptiveTimestep: true
    },
  };

// -------------------------------------------------------------------------
// IMPORT DATA FROM EXTERNAL JSON FILE:

// Per: https://github.com/ikwattro/blog/blob/master/sources/easy-graph-visualization-with-vis-dot-js.adoc:

// NOTES:
// 1. Must use double quotes ("; not ') in that JSON file;
// 2. Cannot have comments in that file, only data!  See:
//    https://stackoverflow.com/questions/244777/can-comments-be-used-in-json
// 3. Per the path below, place the "test.json" file in a "data" subdirectory.

var json = $.getJSON("data/test.json")
  .done(function(data){
    var data = {
      nodes: data.nodes,
      edges: data.edges
    };
    var network = new vis.Network(container, data, options);
  });

var container = document.getElementById('mynetwork');

</script>

</BODY>
</HTML>

test.json

{"nodes":[
  {"id":"1", "label":"Node 1"}
  ,{"id":"2", "label":"Node 2\nline 2"}
  ,{"id":"3", "label":"Node 3"}
  ,{"id":"4", "label":"Node 4"}
  ,{"id":"5", "label":"Node 5"}
],
"edges":[
  {"from":"1", "to":"2", "label":"apples"}
  ,{"from":"1", "to":"3", "label":"bananas"}
  ,{"from":"2", "to":"4", "label":"cherries"}
  ,{"from":"2", "to":"5", "label":"dates"}
  ,{"from":"2", "to":"3", "label":"EAGLES!", "color":{"color":"green", "highlight":"blue"}, "arrows":{"to":{"scaleFactor":"1.25", "type":"circle"}}}
]
}

Output

vis.js - Network from JSON data.png

like image 75
Victoria Stuart Avatar answered Sep 23 '22 10:09

Victoria Stuart