When loading JSON data dynamically into a D3 network visualization, the links may not be immediately visible

In my possession is a json file containing nodes and links defined with source and target attributes.

    {
    "links":[
        {"_id": "5a4b2866235fa755b6576903", "target": 6746, "source": 2169},
        {"_id": "5a4b2866235fa755b65768e3", "target": 6746, "source": 6357},
        {"_id": "5a4b2866235fa755b6576641", "target": 7045, "source": 8590}
            ],

    "nodes":[
        {"_id": "5a4b281e235fa755b6576340", "id": 6746, "Citation": "Chandler", "citedNo": "0", "size": 10},
        {"_id": "5a4b281d235fa755b657447f", "id": 1195, "Citation": "Aaron", "citedNo": "0", "size": 0},
        {"_id": "5a4b281e235fa755b657591f", "id": 4438, "Citation": "Chris", "citedNo": "0", "size": 10},
        {"_id": "5a4b281e235fa755b6575f31", "id": 7045, "Citation": "Brittany", "citedNo": "0", "size": 10},
        {"_id": "5a4b281e235fa755b6575f27", "id": 2169, "Citation": "James", "citedNo": "0", "size": 10},
        {"_id": "5a4b281e235fa755b6575ecb", "id": 6357, "Citation": "David", "citedNo": "0", "size": 10},
        {"_id": "5a4b281e235fa755b6575750", "id": 8590, "Citation": "Kris", "citedNo": "0", "size": 10}
            ]
    }

Upon loading the above data from the file, the links are visible. However, when attempting to load the data dynamically, the links are not displayed.

The reason for dynamic loading is due to a keyword search using ElasticSearch on MongoDB, which generates a json with nodes, links (sources and targets) referenced in the js to create a D3 network visualization.

The need for dynamic loading arises from the limitless search use cases, making it suboptimal to filter and store numerous versions of json files.

Code for creating the arrays:

    var arr = new Object;
    arr["nodes"] = nodearray;
    arr["links"] = linkarray;

Script for building D3 network visualization:

    d3.json('d3datap.json', function(error, graph) {
                      // console.log(JSON.stringify(arr));
                      var graph = JSON.parse(JSON.stringify(arr));
                      console.log(graph.nodes);
                      console.log(graph.links);
                      const width = 1200;
                      const height = 500;

                      const mouseOverFunction = function (d) {
                        const circle = d3.select(this);

                        node.append("text")
                        .attr("x", 12)
                        .attr("dy", ".35em")
                        .text(function(d) { return d.Party; });

                        // More visualization logic here...

                      });

CSS styling:

    .node circle {
          stroke: white;
          stroke-width: 1.5px;
          opacity: 1.0;
        }

        line {
          stroke: black;
          stroke-width: 1.5px;
          stroke-opacity: 1.0;
        }

While the console displays the json data correctly, the links do not appear. I have searched extensively for solutions to the issue of dynamically loading json into D3, but none have resolved my problem. Any assistance in identifying the issue would be highly appreciated.

Answer №1

The function d3.json operates asynchronously. It seems that you have created the object arr somewhere above your json call:

d3.json('d3datap.json', function(error, graph) {
       // graph is passed in, but arr is used??
                  // console.log(JSON.stringify(arr));
                  var graph = JSON.parse(JSON.stringify(arr));

As a result, the arr object may or may not be fully formed when d3 is using it. When you console.log the graph, Chrome updates that object after the asynchronous call completes, so it may seem like it contains all the data when you view it, but d3 is not actually receiving the data. Your code should utilize the graph value that you obtain from the d3.json call.

If you provide additional code regarding how your arr is generated and why it's placed above your d3.json call, I can enhance this answer. Generally, it's preferable to include your entire code block rather than just fragments of it (and it's best to link to a bl.ocks.org or blockbuilder.org or codepen version of the code).

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

Master the Art of Animating Letters in the DOM by Navigating Through Any Array of Characters

I am attempting to implement a typewriter effect animation where a new message is displayed and animated as I type into an input box. Initially, I tried using a global char variable to iterate through each element of the array. However, whenever I passed ...

Close any open alerts using Protractor

While using protractor and cucumber, I have encountered an issue where some tests may result in displaying an alert box. In order to handle this, I want to check for the presence of an alert box at the start of each test and close/dismiss it if it exists. ...

Using NextJS to pass a string from an input field to getStaticProps via context

I am a beginner in NextJS and React, so please forgive my lack of knowledge. I am trying to figure out how to pass the text input by users from an input field (inside Header) to the getStaticProps function of a specific page using the React context API. I ...

Discover the method for displaying a user's "last seen at" timestamp by utilizing the seconds provided by the server

I'm looking to implement a feature that displays when a user was last seen online, similar to how WhatsApp does it. I am using XMPP and Angular for this project. After making an XMPP request, I received the user's last seen time in seconds. Now, ...

Manipulating nested JSON objects with AngularJS by adding and pushing the data

I am looking at a JSON object structured like this : { "Name": "Shivansh", "RollNo": "1", "Stream": "CSE", "OverallScore": "76", "Semester": [ { "SemesterName": "FY-2012 - 1", "TotalScore": "78.00", ...

Leveraging Jackson databind grants the flexibility to designate certain fields as optional during the deserialization process of a string, while mandating others

I am currently utilizing jackson-databind-2.9.8.jar. Here is the Java class representation of the model that will store the deserialized JSON String. @JsonIgnoreProperties(ignoreUnknown = true) public class CustomClass { @JsonProperty("key-one") ...

Master the art of manipulating JSON arrays with jQuery

Looking to extract the information with a specific key and payment value from a JSON array generated by an API request. The desired data is: "Key":"PCP","Payment":170.08 The array in question looks like this: {"VehicleResults":[{"Id":"0","FinanceProduct ...

Double injection of Redux-saga

I've encountered a strange issue with my redux-saga - it's being called twice instead of just once. Here is the action that triggers the saga: export function createRequest (data) { return { type: CREATE_REQUEST, payload: {data} }; ...

Obtaining the Etag for a Restheart collection: A step-by-step

I'm attempting to remove a collection using the Restheart API. $http DELETE 127.0.0.1:8080/testDB/testCollection However, I encounter the following error: "The collection's ETag must be provided using the 'If-Match' header." If ...

Display the closing tag depending on specific conditions to simulate the behavior of a calendar

Is it possible to conditionally render a closing tag using v-if? If so, what is the correct way to do it? Initially, I tried the following: <template v-for="day in days"> <td class="days">{{day.number}}</td> <template v-if ...

Combining Data in React Arrays

I have an array with different group types and I need to merge the results if the grouptype is the same. const locationss = [ { grouptype: "Name1", id: "1", servicetype: [ { name: "Morning", price: "5& ...

What is the best way to ensure that custom JavaScript and CSS files in Sphinx are always loaded with the most recent changes

Within the configuration file conf.py for Sphinx, I have specified the following: html_css_files = ['css/custom.css'] html_js_files = ['js/custom.js'] However, any alterations made to custom.js or custom.css do not immediately appear i ...

Is there a way to split the text into distinct pages within a contenteditable area, similar to the functionality in Google Docs

I've been working on developing a specialized browser-based text editor and I've encountered a puzzling question. How can I detect and split long texts into separate pages, similar to how Google Docs handles pagination? I'm aware that Google ...

Creating a user interface to display different game options using Hooks (Developing an interactive rock-paper-scissors game)

I'm currently experimenting with React.js hooks while creating a new version of the classic game "Rock Paper Scissors." I'm facing an issue where the winner is not evaluated immediately after pressing the respective button. Below is a snippet of ...

Differences in accessing the previous state between React's useCallback and useState's setState(prevState)

It has come to my attention that useCallback functions recreate themselves when their dependencies change, acting as a sort of wrapper for memoizing functions. This can be particularly useful for ensuring access to the most up-to-date state in useEffect ca ...

Is there a possible class-related problem if updating the 'username' field in flask-login with MongoDB logs the user out?

Currently, I am working on my Flask application that utilizes flask-login and PyMongo. In my project, I have a class for the user and a loader function as shown in the users.py file: from werkzeug.security import check_password_hash from app import login, ...

What is the best way to deliver HTML content to an ASP.NET MVC JSON function?

Here is my jQuery code that I have written along with the json function called InsertMatlabJson. However, I am facing an issue where no text is being passed to the .NET json function. function insert() { var url = '<%=Url.Content( ...

Double-reading the request body in Golang

type ValidationModel struct { Name string `json:"name" valid:"alpha,required~Name is required"` Email string `json:"email" valid:"email~Enter a valid email.,required~Email is required."` Password string `json:"password" valid:"required~P ...

What's the best approach: Backbone-Relational discovery or retrieval?

Although the model caching feature in Backbone-Relational is effective, loading a simple model securely requires considerable code. For example: // Attempt to locate a model in the cache this.model = MyModel.find({id:id}); if(this.model){ // Model re ...

Guide to incorporating a vector 2 while serializing with JSONcpp

I am trying to convert a vector of Books into json format using jsoncpp. Despite following the model provided in this tutorial on Stack Overflow which uses a map, I am having trouble getting my data in the desired json format. struct Book { std::string bo ...