Utilize JSON data in d3.js for creating a scatterplot visualization

I have recently started working with d3.js and I'm facing some challenges. From what I understand, the second parameter passed in d3.json() is used to process data from a JSON file.

Here is my code:

d3.json(base_url() + "data/data.json", clean_data)
   .then(function (dataset) {
      global_dataset = dataset;
      console.log(dataset.age);
  })
 .catch(() => console.log("could not load a file"));

function clean_data(d) {
 console.log("i am here");
 let balance = d.balance;
 balance = balance.splice(1);
 return { age: +d.age, balance: +balance };
}

When I run this code, the console.log(dataset) displays the original JSON data instead of the processed object returned by the clean_data() function.

This is how my JSON data is structured:

JSON URL

In the HTML file where this code resides, I have included the CDN link for d3.js :

<script src="https://d3js.org/d3.v5.min.js"></script>

My goal is to create a scatterplot using this JSON data with d3.js and promises.

Answer №1

It appears that you may have misunderstood the usage of d3.json(). In version 5, d3.json() requires the URL as the first parameter and an option object as the second parameter (as d3.json is a wrapper for the fetch API). This function returns a Promise that is resolved upon success and rejected upon failure. You need to iterate over the JSON response and store it in an Array or utilize D3.js - enter(), update() and exit() pattern. Here is an example:

const data = [];

d3.json('https://next.json-generator.com/api/json/get/V1OqfcoK_')
 .then(function (dataset) {
   dataset.forEach((d, i) => {
     data.push({age: +d.age, balance: +Number(d.balance.replace(/[^0-9.-]+/g, ""))});
   });
   // Once iteration is complete, use the data
   console.log(data);
})
.catch(() => console.log("Could not load the file"));
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v5.min.js"></script>

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 AJAX email submission form is not functioning properly

Recently, I have upgraded my email sign-up form on the website to include validation. However, after adding the validation, the form no longer sends and an error message is not displayed. Upon inspecting, I found the following error: TypeError: null is ...

Facing unexpected behavior with rxjs merge in angular5

import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/merge'; this.data = this.itemsCollection.valueChanges() this.foo = this.afs.collection<Item>('products') .doc('G2loKLqNQJUQIsDmzSNahlopOyk ...

AngularJS $scope variable issue

After searching online, I found this code snippet that I tried to implement, but unfortunately, it's not displaying any data. Below is the HTML code: <html data-ng-app=""> <head> <title>Example 4: Using AngularJS Directives an ...

Unable to view new content as window does not scroll when content fills it up

As I work on developing a roulette system program (more to deter me from betting than to actually bet!), I've encountered an issue with the main window '#results' not scrolling when filled with results. The scroll should always follow the la ...

Find the value of a JavaScript string variable using an alternative name

My latest JavaScript function is designed to fetch JSON data from either a server or local files on any browser. This piece of code processes JSON from two sources: an XMLHttpRequest response, or a variable imported via script. In the case of the latter, ...

Executing a function with the initial click

Is there a way to run a function only on the first click, without having it run every time? I already have another function running on window.onload, so I can't use that. Both functions work fine independently, but not together. Right now, I'm ca ...

Assign a predetermined value to a dropdown list within a FormGroup

I have received 2 sets of data from my API: { "content": [{ "id": 1, "roleName": "admin", }, { "id": 2, "roleName": "user", }, { "id": 3, "roleName": "other", } ], "last": true, "totalEleme ...

The process of transferring ViewBag value as a parameter in an AngularJS function

I'm facing an issue where the viewbag value is not being passed as a parameter in ng-init. Can someone guide me on how I can successfully pass the viewbag value as a parameter? angular.js { $scope.detail = function (Id) { ...

What benefits does JavaScript offer with the strategy of storing functions within variables?

Lately I've come across some code where functions are being stored inside variables and then called in the typical way. For example: var myFunctionName = function() { Code Here... } myFunctionName(); I'm aware that there may be numerous b ...

Check an image preview prior to uploading through FileReader, rotates the image

After browsing through numerous posts about viewing images before uploading, I stumbled upon an intriguing solution that claimed to be simple using FileReader: function displayImage(input) { if (input.files && input.files[0]) { var reader = ne ...

ng-grid cell onclick callback

Currently, I am working with ng-grid and am attempting to define a callback function for when a cell is clicked. During this callback, it is crucial for me to identify the specific row and column of the cell that was clicked. Upon exploring various options ...

Ionic - encountering crashes with ion-nav-view on emulator

I am encountering an issue with ion-nav-view. Whenever I try to use it, the emulator displays a black screen, but it works perfectly fine in ionic serve. I suspect it may be a syntax error causing this problem. Interestingly, when I create a blank projec ...

Encountering a Null Pointer Exception while working with List Adapter and Custom List View in Android Studio

I've been working on developing an app in Android Studio that involves parsing a JSON document and displaying two TextViews of data for each instance - Signal and Noise. I'm attempting to create a custom list view to potentially add more detail t ...

What is the best way to set the page title on a server-rendered component when using the Next.js app router?

When loading a blog post from the server, I have access to details like the title of the post. However, based on the app router migration guide, this information is located outside my page. How can I update it? For more information, refer to the documenta ...

Error message: After using gulp-npm-dist to copy only the dependency modules, the node module was not

I'm currently exploring different methods to package only the necessary node_modules dependencies for my project. After some research, I came across gulp-npm-dist and created a gulpfile.js. var gulp = require('gulp'); var npmDist = requir ...

Unable to retrieve Java variable in JavaScript

Seeking guidance on how to retrieve Json data stored in a Java variable using JavaScript. Instead of accessing the data, the html source is displayed. Java: Gson gson = new Gson(); String json = gson.toJson(obj); request.setAttribute("gsonData", gson) ...

Highlighted option selection in Material UI dropdown using Cypress

Can someone explain how to select Material-UI dropdown options using Cypress? I'm looking for a simple explanation, thanks! ...

Token generated by Sinch backend for use with Javascript and Android applications

I am currently exploring two distinct methods for creating the sinch authentication token on an app server. One approach is designed for the Android client while the other is tailored for the JS client. Is it feasible to utilize the same token for both the ...

Converting JavaScript numbers into years and months format

Given an integer, for example 20, I am trying to calculate how many months and years are represented by that number. For 20, the result would be 1 year and 8 months. How can this be achieved using JavaScript? switch (props.term) { case (props.term ...

When combining CSS grids, nesting them can sometimes cause issues with the height layout

Check out the code on jsFiddle .component-container { width: 800px; height: 200px; background-color: lightyellow; border: 1px solid red; padding: 10px; overflow: hidden; } .component-container .grid-container-1 { display: grid; grid-tem ...