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

What are the steps to lift non-React statics using TypeScript and styled-components?

In my code, I have defined three static properties (Header, Body, and Footer) for a Dialog component. However, when I wrap the Dialog component in styled-components, TypeScript throws an error. The error message states: Property 'Header' does no ...

"Revolutionize real-time data updates with Node.js, Redis, and Socket

Greetings! I am currently working on a project for my school that involves creating a "Twitter clone." My goal is to incorporate a publish subscribe pattern in order to facilitate real-time updates. One key feature users will have access to is the abili ...

What is the importance of using explicit casting in Java when dealing with JSON parsing or processing webservice responses?

Trying to extract and interpret Json response from the Google GeoCoding API using org.JSON within Java. The response stream can be either a JSONObject or JSONArray according to API specifications. Q1: The need to explicitly cast them each time (as shown i ...

PHP: Utilizing foreach() to extract data from JSON

I attempted to decode a JSON file and exhibit its contents. The PHP code I used is: <?php $proj = json_decode(file_get_contents('projects.json')); foreach ($proj->projs as $p) { $name = $p->name; $auth = $p->autho ...

Is there a way to determine the distance in miles and feet between various sets of latitude and longitude coordinates?

I am working with an array of latitude and longitude coordinates and I am looking to use JavaScript or Typescript to calculate the distance in miles and feet between these points. const latsLngs = [ { lat: 40.78340415946297, lng: -73.971427388 ...

Axios is causing my Pokemon state elements to render in a jumbled order

Forgive me if this sounds like a silly question - I am currently working on a small Pokedex application using React and TypeScript. I'm facing an issue where after the initial page load, some items appear out of order after a few refreshes. This make ...

Did you manage to discover a foolproof method for the `filesystem:` URL protocol?

The article on hacks.mozilla.com discussing the FileSystem API highlights an interesting capability not previously mentioned. The specification introduces a new filesystem: URL scheme, enabling the loading of file contents stored using the FileSystem API. ...

Troubleshooting React-Redux: Button click not triggering action dispatch

I am facing an issue where my action is not being dispatched on button click. I have checked all the relevant files including action, reducer, root reducer, configStore, Index, and Component to find the problem. If anyone can help me troubleshoot why my a ...

Why is a <script> tag placed within a <noscript> tag?

Lately, I've been exploring various websites with unique designs and content by inspecting their source code. One site that caught my attention was Squarespace, which had blocks of <script> tags within a <noscript> tag: <!-- Page is at ...

I keep encountering an error that says "ReferenceError: localStorage is not defined" even though I have already included the "use

I have a unique app/components/organisms/Cookies.tsx modal window component that I integrate into my app/page.tsx. Despite including the 'use client' directive at the beginning of the component, I consistently encounter this error: ReferenceErr ...

Issue with CSS: Dropdown menu is hidden behind carousel while hovering

I'm struggling with adjusting the position of my dropdown list. It keeps hiding behind the carousel (slider). When I set the position of the carousel section to absolute, it causes the navbar to become transparent and the images from the carousel show ...

Is my Discord.js bot malfunctioning due to incorrect indentation, despite the absence of errors?

After spending a considerable amount of time developing this bot, I encountered an issue following an update that introduced 'limitedquests'. Previously, the bot worked flawlessly but now, certain functions are not functioning as intended without ...

Passing a parameter in JSON format is made easy with RestEasy when making a POST request

I am working with a REST endpoint that looks like this: @POST @Path("/id/{id}/doSomething") @Produces({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON }) public Response doSomething(@PathParam("id") final String id, MyObject foo) { ...

A guide on transforming JSON data to an array format where nested arrays are encapsulated within objects using curly braces instead of square brackets in TypeScript

Retrieve data from a REST API in the following format: { "ProductID":1, "Category":[ { "CategoryID":1, "SubCategory":[ { "SubCategoryID":1, } ] } ] } I need to t ...

What is the best way to trigger ajax when the user clicks the back button to return to the previous webpage?

Check out my code snippet below: HTML Code <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="body"> <div class="dropdown_div"> <select id="q_type" class="dropdown" ...

Custom headers in XmlHttpRequest: Access control check failed for preflight response

Encountering an issue with an ajax GET Request on REST Server. Test results and details provided below. There are two methods in the REST Server: 1) resource_new_get (returns json data without custom header) 2) resource_api_new_get (also returns json d ...

Is there a way to link the output to the attributes of the constructor in C#?

Developing an interface with the following properties: public interface IDatasource { string Name { get; } string Description { get; } List<GraphPoint> Point { get; set; } } After implementing this interface, I crea ...

Angular5+ Error: Unable to retrieve summary for RouterOutlet directive due to illegal state

When attempting to build my Angular App using ng build --prod --aot, I consistently encounter the following error: ERROR in : Illegal state: Could not load the summary for directive RouterOutlet in C:/Path-To-Project/node_modules/@angular/Router/router.d. ...

Change the boxShadow and background properties of the material-ui Paper component

I am currently referencing their documentation found at this link in order to customize default Paper component properties. Below is the code snippet I have: import { styled } from '@mui/material/styles'; import { Modal, Button, TextField, Grid, ...

What is the correct way to utilize the WhatsApp API for sending messages?

Trying to incorporate WhatsApp API notifications into my app has been a challenge. Despite extensive research, I have yet to find an official solution. The existence of the WhatsApp API Business is known, but it currently remains in beta and caters to com ...