Utilize a JSON file to generate a network visualization using the vis.js library

I am currently working with vis.js to generate a visualization. In the example code, I am using the file saveAndLoad.html. The save function works well as it allows me to export a json file. However, I am encountering an issue when trying to load the json file using the import function, as it does not create the desired mapping for me. I am unsure where my misunderstanding lies and would appreciate any assistance. Below is the code for 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();
        }

Answer №1

After spending a significant amount of time searching for a solution, I finally managed to figure out how to load an external JSON datafile into a vis.js Network. Here is the working solution that I came up with.

To learn more about my process and details, check out the comments in the HTML file below:

  • I opted to install vis.js via NPM, but it's also possible to just download or source the vis.min.js file;

  • The code provided by visjs.org in the "full options" tab for the Network module edge options turned out to be buggy due to extra commas, etc. I included a corrected version in my HTML code (same goes for the "physics" options).

  • As mentioned in the comments within my HTML file, formatting the JSON datafile is crucial: make sure to use double quotation marks; curly braces { } should not be quoted (especially when defining per-edge attributes in the 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

https://i.stack.imgur.com/6Y5Lv.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transforming varied JavaScript objects into a serial form

In my application, there is a concept of an interface along with multiple objects that implement this interface in various ways. These objects are created using different factory methods, with the potential for more factories to be added as the application ...

I am facing a dilemma with Expressjs when it comes to managing numerous users simultaneously

I'm grappling with a conceptual dilemma as I delve into the world of building an expressjs app. My goal is to create a system where each user, upon starting the app, has their own temporary folder for storing various files. Despite my lack of experien ...

Is there a way to retrieve the Marker that is being dragged when the event handler has already been bound?

How can I identify the Marker that is being dragged when the handler is a bound function? Take a look at this snippet from my react component: constructor() { this.handleMarkerMove = this.handleMarkerMove.bind(this); } createMarker() { const marker ...

What causes jQuery's .width() method to switch from returning the CSS-set percentage to the pixel width after a window resize?

After exhaustively console logging my code, I have finally identified the issue: I am attempting to determine the pixel width of some nested divs, and everywhere I look suggests that jQuery's .width() method should solve the problem. The complication ...

Error encountered in Ubuntu while attempting to run a Python script within a Node.js/Express application: spawn EACCES

Recently, I set up a node.js server to run a python script using the python-shell . However, after migrating from Windows to Ubuntu, an EACCES error has been persistently popping up. Despite my attempts to adjust permissions and troubleshoot, I haven' ...

Are NPM and Eslint supposed to be this confusing, or am I missing something?

Recently, I've started delving into the world of JS and have been eager to learn more about linting. Following a tutorial, we set up the lint stage in our package.json file. The configuration looks like this: "lint": "./node_modules/.bin/eslint ." U ...

Creating dynamic form fields using AngularJS

I have a form that includes an input field, a checkbox, and two buttons - one for adding a new field and one for deleting a field. I want to remove the add button and instead show the next field when the checkbox is checked. How can I achieve this? angu ...

A guide to setting up automatic version numbering in package.json using Jenkins

My package.json is structured like this: { "name": "Myproject", "version": "0.4.13", Note: Here 4 is not considered the minor version, instead it's 0013. "dependencies": { "lodash": "^4.0.0", "vinyl-fs": "2.2.1" }, "r ...

React Native not refreshing state data

I'm working with a FlatList that contains the code snippet below: <FlatList ........... refreshing={this.state.refresh} onRefresh={() => { this.setState({ ...

Utilize flexbox to create a list that is displayed in a column-reverse layout

I am facing a challenge in displaying the latest chat person in the 1st position (active) using Firebase. Unfortunately, Firebase does not have a date field which makes it difficult to achieve this. I have attempted converting the date into milliseconds an ...

Guide to accessing HTML elements and saving them in a JSON formatted text using JavaScript

If you have an html form with labels, select boxes, and radio buttons, you can use javascript to store the child elements of that form in a json string format. Here is an example: { "label": { "content": "This is a label" }, "textbox" ...

Ensuring continuous execution of JS EventListener

The other day, I received a solution from someone on this platform for a script that changes the color of a div when scrolling. Here is the code I implemented: const x = document.getElementById("menuID"); window.addEventListener("scroll", () => { ...

Expanding circle with CSS borders on all edges

My goal is to create a background reveal effect using JavaScript by increasing the percentage. The effect should start from the center and expand outwards in all directions. Issue: The percentage increase currently affects only the bottom and not the top ...

Is there a way in Reactjs Material UI 5 (MUI5) to unselect only the star that was clicked, without affecting the rest of the stars in the

For instance: I selected the 3rd star on the rating component, but when I click on it again, all the previous stars disappear and it shows 0 stars. How can I make it so that if I click on the 3rd star a second time, only the 3rd star is removed, leaving ...

Transferring user-selected values from JavaScript to a PHP file

When sending values from JavaScript to a PHP file, everything works smoothly when all the values are collected. Step1 functions perfectly as both fields are mandatory. However, in Step2, values are only sent when all the fields are selected. There are co ...

Selenium and AngularJS patiently wait before carrying out specific actions

I have been using selenium to test an AngularJS application and I am encountering an issue where I am unable to perform any actions on the page until it is fully loaded. Although I have considered using Thread.sleep(), I am aware that this is not the most ...

JavaScript OOP Function call not functioning in IE9

When using IE9, a JavaScript OOP Function call does not seem to work for me. Here is my code snippet: var newobj = new SAObject(); <input onclick="newobj.function()" /> Upon clicking the button, nothing happens. No alert is displayed, and it seem ...

Creating NextJS Route with Dynamic Links for Main Page and Subpages

In my NextJS project, I have dynamic pages and dynamic subpages organized in the following folders/files structure: pages ├── [Formation] ├── index.js │ ├── [SubPage].js Within index.js (Formation Page), I create links like this: < ...

Enclosing values in JavaScript literals

I apologize for the inconvenience. I am unsure why it is not functioning properly. If I input <button type="button" onclick="document.getElementById("demo").innerHTML = Date()">click</button> the above code does not work. However, if I u ...

Tips for toggling the visibility of a revolution slider based on current time using JavaScript

Currently, I am integrating the revolution slider into my WordPress website. My goal is to have the slider change according to the standard time of day. For instance, I want slider1 to display in the morning, slider2 at noon, slider3 in the evening, and sl ...