Utilizing d3.json: changing the URL with dynamic data

Just getting started with d3 and building a sankey diagram. I came across a sample that uses an external .json file with d3.v3, even though it is an outdated version. Since my tree also relies on this version, I'd like to stick to just one d3 version. The sankey diagram is functioning properly, but now I want to swap out the static json data with dynamic data fetched from a database. My plan is to load the page, query the database, fetch the data, format it as an array of objects, and then pass it to the sankey code.

To ease into the changes, I've copied the contents of the json file and inserted them directly into my page.

var MYDATA = {
"links": [
{"source":"Agricultural Energy Use","target":"Carbon Dioxide","value":"1.4"},
{"source":"Agriculture","target":"Agriculture Soils","value":"5.2"},
{"source":"Agriculture","target":"Livestock and Manure","value":"5.4"},
{"source":"Agriculture","target":"Other Agriculture","value":"1.7"},
...
};

The relevant section of the sankey code where the file is loaded looks like this:

d3.json("#APP_FILES#sankeygreenhouse.json", function(error, graph) {
    var nodeMap = {};
    graph.nodes.forEach(function(x) { nodeMap[x.name] = x; });
    graph.links = graph.links.map(function(x) {
      return {
        source: nodeMap[x.source],
        target: nodeMap[x.target],
        value: x.value
      };
    });

I am attempting to modify this to use MYDATA instead of '#APP_FILES#sankeygreenhouse.json'. However, when I changed the line to

d3.json(MYDATA, function(error, graph) {

I encountered a 404 error. What steps should I take to make this work?

Answer №1

Using d3.json to load a file and store it as an object called graph. However, you can skip this step and directly assign the loaded data to MYDATA instead.

Instead of:

d3.json(MYDATA, function(error, graph) {
    var nodeMap = {};
    graph.nodes.forEach(function(x) { nodeMap[x.name] = x; });
    graph.links = graph.links.map(function(x) {
      return {
        source: nodeMap[x.source],
        target: nodeMap[x.target],
        value: x.value
      };
    });
//...
})

You can use:

var nodeMap = {};
var graph = MYDATA;
// or if you want to make a copy:
// var graph = structuredClone(MYDATA);

graph.nodes.forEach(function(x) { nodeMap[x.name] = x; });
graph.links = graph.links.map(function(x) {
   return {
    source: nodeMap[x.source],
    target: nodeMap[x.target],
    value: x.value
   };
});

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

The state returned by React Redux does not meet the expected results

I recently implemented a like function on the backend using Node and MongoDB. This function successfully returns the post with an updated likes counter, which I tested using Postman. The post object contains properties such as likes, _id, by, createdAt, an ...

Executing a function defined in a .ts file within HTML through a <script> tag

I am attempting to invoke a doThis() function from my HTML after it has been dynamically generated using a <script>. Since the script is loaded from an external URL, I need to include it using a variable in my .ts file. The script executes successfu ...

Tips for navigating to an external website through GraphQL

I am currently utilizing Node.js and Front-end on Next.js. I have a GraphQL server with a GetUrl method that returns a link (for example: ""). My goal is to redirect a client who made a request to that page with a Basic Auth Header. From what I understan ...

Display "No information found in table" message using the Jquery DataTables plug-in after sorting or filtering the data

When retrieving data from the server to populate a DataTables table, I utilize the JSON format. Upon checking the Success section of the $().ajax function, it is evident that the response is coming back successfully. Here is the link to view my table on F ...

Looking for assistance with removing hardcoding in HTML and jQuery?

Currently working on a biography page for my company's website that features a grid layout of the employees' profile pictures. Each picture should be clickable, causing the screen to fade to gray and display an overlay with the respective person& ...

What is the most effective way to perform two GET requests in PHP?

Here's the code snippet I am currently working on: $header = [ 'phoneType' => $mobileType ]; \Drupal::logger("cam")->debug('PageNameHere retrieveAPINameHere REQUEST: '.json_encode($head ...

Vue's span function is yielding the promise object

In my Vue component, I am using the function getOrderCount to fetch the number of orders from a specific URL and display it in one of the table columns. <div v-html="getOrderCount(user.orders_url)"></div> async getOrderCount(link) { ...

Saving JSON objects within key-value fieldsORStoring a JSON object

I have a specific data structure designed to store data in a JSON format. The structure looks like this: { "NVPS": [ "NAME": "formData", "VALUE" : "myData" ] } To serialize a large object containing sub-objects into a string and place it in the 'VAL ...

What is the process for connecting a Wii Remote with Three.js?

Suppose I wanted to explore Wii Remote to browser interaction by connecting it to my Ubuntu laptop via Wiican and Wmgui using Bluetooth. What would be a simple program to achieve this? I have successfully used an Xbox Gamepad with Chrome, so I know that i ...

Winston is set up to only record .info errors and does not save any errors to a file or a MongoDB database

Currently, I am utilizing express-mongoose as my backend framework and winston as my logging tool. However, I have encountered an issue where winston only seems to log info messages and not errors. The logs can be found in server.log https://i.stack.imgur. ...

Tips for utilizing an npm package in conjunction with Hugo

I created a basic hugo site with the following command: hugo new site quickstart Within the layouts/_default/baseof.html file, I have included a JavaScript file named script.js. Inside script.js, the code looks like this: import $ from 'jquery' ...

Create a generic function that retrieves a specific property from an array of objects using the select method

Currently, I have implemented four functions that select entries from an array based on different properties. if ($scope.filters.filter1) $scope.filteredEntries = $scope.filteredEntries.filter(function (o) { return o.field1 === $scope.filt ...

Learning to interpret the attributes of a struct field

One of the key features in my package is the ability for users to define the backend database column name explicitly for their fields, if they choose to do so. Normally, the package uses the field's name as the column name. However, there are cases w ...

Tips for choosing a class with a leading space in the name

Struggling with an issue here. I'm attempting to adjust the CSS of a specific div element that is being created dynamically. The current output looks something like this: <div class=" class-name"></div> It seems there is an extra space b ...

Is it possible to include a while loop for iteration inside a AJAX success function?

I'm currently working on dynamically creating an accordion and populating the content of each tab using AJAX. In my main HTML page, there is an empty div reserved for the accordion: <div id="accordion"></div> The desired outcome is to ha ...

Tips for updating model data when integrating jQuery Data tables with ASP.NET MVC

Managing a large amount of data returned from JSON can be complex. To tackle this, I am utilizing jQuery dataTable for sorting, filtering, and pagination purposes. The functionality is working seamlessly for sorting, searching, and paginating the data. H ...

Creating a shared function using TypeScript

Having a vue3 component that displays a list of items and includes a function to delete an item raises a concern about checking parameters and specifying the array for the filter operation. The goal is to create a universal function using typescript. <t ...

The JSON output is only displaying the final object in the array

Currently, I am working on creating a custom JSON feed for my WordPress page. The issue I am facing is that the loop seems to be overwriting every object, resulting in only the last object being printed as JSON. I have attempted moving the echo inside the ...

Show a Bootstrap Json tree structure

Hello, I am a newcomer to AngularJS and I am looking for a way to display JSON data in a tree structure that can be expanded and collapsed with the click of a button. I have tried several npm plugins but haven't found one that satisfies my needs. Can ...

Calculate the date and time three months before or after a specified date

I have the following start date : 2023-09-03T00:00:00+05:30 and end date : 2023-09-10T00:00:00+05:30 My objective is to deduct 90 days from the start date and add 90 days to the end date Afterwards, I need to convert it to UTC format In order to achieve ...