There was a problem encountered while trying to load the .json/.csv file

Attempting to grasp D3 through this video has been a challenging experience, particularly when attempting to load an external file. The code snippets are provided below:

index.html

<html>
  <head>
  <meta charset="utf-8">
    <title>D3 Example</title>
  <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script>
  <body>

    <script>
    d3.json("mydata.json", function(data){

      var canvas=d3.select("body")
        .append("svg")
          .attr("width", 500)
          .attr("height", 500);

      canvas.selectAll("rect")
        .data(data)
        .enter()
        .append("rect")
          .attr("width", function(d){return d.age*10;})
          .attr("height", 50)
          .attr("fill", "blue")
          .attr("y", function(d,i){return i * 60});

      canvas.select("text")
        .data(data)
        .enter()
        .append("text")
          .attr("fill", "white")
          .attr("y", function(d, i){return i * 60})
          .text(function(d) {return d.name;});
        });
</script>
</body>
</html>

mydata.json

[
  {"name": "Maria", "age": 30},
  {"name": "Fred", "age": 50},
  {"name": "Francis", "age": 12}
]

Running it on a server yields:

app.js

const http=require('http');
const fs=require('fs');

const hostname='127.0.0.1';
const port=3000;

fs.readFile('index.html', (err, html) => {
  if (err) {
    throw err;
  }

  const server = http.createServer((req, res) => {
    res.statusCode =200;
    res.setHeader('Content-type', 'text/html');
    res.write(html);
    res.end();
  });

  server.listen(port, hostname, () => {
    console.log('Server started on port '+port);
  });
});

The persistent error message received is:

Uncaught TypeError: canvas.selectAll(...).data(...).enter is not a function

Switching to D3 version 3 results in the error:

Uncaught TypeError: Cannot read property 'length' of null

Furthermore, attempting to load a .csv file triggers the following error:

Error: attribute width: Expected length, "NaN".

Answer №1

Your server setup is causing the error you are experiencing. Regardless of what content you request, the server will always respond by sending the contents of index.html. Even if you ask for mydata.json, you will still receive the contents of index.html.

Since the file being returned does not contain valid JSON data, it cannot be parsed correctly by d3.json(). This results in the callback's data parameter becoming null. When you pass null to .enter(), it behaves as agetter in your case, returning an empty array:

If data is not specified, this method returns the array of data for the selected elements.

As a result, the array obtained does not have a .enter() method, leading to the error.

var data = d3.selectAll("div")
  .data(null);

console.log(data);          // []: Empty array
console.log(data.enter());  // "Uncaught TypeError: data.enter is not a function"
<script src="https://d3js.org/d3.v4.js"></script>

To resolve this issue, ensure that your server is set up properly to return the correct content.


In addition, for better code robustness, consider implementing error handling during loading or parsing processes. These errors can be managed within the callback provided to d3.json():

The callback is invoked with two arguments: the error, if any, and the response value. The response value is undefined if an error occurs.

Although not compulsory, incorporating error checks can simplify debugging.

d3.json("mydata.json",function(error, data) {
  // Handle error (logging, throwing, whatever)
  if (error) throw error;
}

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

Calculating the mean value of the numbers provided in the input

I'm struggling with calculating the average of numbers entered through a prompt window. I want to display the numbers as I've done so far, but combining them to find the average is proving difficult. Here's the code I have: <html> &l ...

Attempted to execute my testing script with mocha, however encountered a "Reference Error: beforeEach is not defined" issue

While running my test script for a todo app in node.js using Mocha, I encountered a reference error stating that "beforeEach is not defined". The code snippet causing the issue is shown below: const {app} = require('./../server'); const {Todo} ...

What is the best way to implement my Vanilla JS Array manipulation technique in a ReactJS environment?

My REST API development is in its final stages, and I'm currently facing a challenge with converting an array received from the backend into either a Nested Object of Objects or an array of objects. This conversion would allow me to avoid directly acc ...

Troubleshooting issues with Vue CLI 4 and A-Frame: Finding solutions for

Recently, I've been working on creating a VR web app using Vue cli 4.2.3 and aframe.io. However, I encountered numerous error messages related to aframe's components. [Vue warn]: Unknown custom element: <a-scene> - did you register the com ...

Remove the array element if the value is blank

I have an array with different objects, and I need to efficiently delete the entries where the name is empty, similar to the first and third object in the example below: var myArray = [ { "Name": "", "Value": "" }, { "Name": "aaa", "Value": "bbb" ...

Decode array in JavaScript

Hello, I'm currently trying to deserialize this array in JavaScript using the PHPunserialize module: a:7:{s:13:"varPertinence";a:4:{i:0;s:5:"REGLT";i:1;s:2:"13";i:2;s:2:"15";i:3;s:2:"16";}s:10:"varSegment";N;s:12:"varSSegment1";N;s:12:"varSSegment2"; ...

I'm struggling to figure out how to specify the data type for storing an array of objects in a variable using React.useState

I am currently working on extracting values from an .xlsx file using the SheetJS library. Below, I will provide the code snippets, errors encountered, and the different approaches I have attempted. Data extracted from var dataToJson: (6) [{…}, {…}, { ...

Unlocking the secrets of JSON data extraction with Oracle text indexing

I have a table with an Oracle text index specifically created to enhance search speed. The table stores JSON data, and I found that the Oracle json_textcontains function is not performing well enough for my needs. As a result, I experimented with using CON ...

Tips for accessing an Angular service from different Angular controllers

I am a beginner with angular js and I am currently exploring ways to call the service provided in the code snippet below from a controller. The service is defined as follows. app.factory('myappFactory', ['$http', function($http) { v ...

Executing Java Script on several identical elements

Currently, I am facing an issue with my JavaScript function that is supposed to toggle the display of titles within elements. The function works perfectly fine on the first element, but it does not work on the other elements. Here is the code snippet: ...

Fixing the issue of 'Unrecognized character < in JSON at position 0 at JSON.parse'

I have recently deployed my Angular 6 application on Heroku at . However, upon deploying, I encountered the error message: SyntaxError: Unexpected token < in JSON at position 0 during JSON.parse. I am aware that this error occurs when the response ret ...

What is the ideal way to utilize Vue within the framework of multiple pages?

When using the default Vue CLI setup, Vue is loaded from the index.html page. To work with Vue and dynamic content on the page, everything is typically handled in the App.vue file. But what if you want to make significant layout changes to the page? How d ...

Trouble with updating a variable within a loop in Cypress

During my experience with writing Cypress tests, I came across an issue that is preventing me from updating a specific variable. The goal of my test is to run a loop and update the questionId variable within each iteration for making API queries. However, ...

Require a v-alert notification to appear on every page, ensuring visibility across the site

Imagine a scenario where there is a right drawer that displays a grade dropdown with options like grade1, grade2, and grade3. On all pages, I need a v-alert notification strip to show the total count of students. For example, if I select grade3 from the ri ...

Issue with displaying dates correctly when retrieving data from an external CSV using Highcharts (Highstock)

I have been struggling for several days to integrate Highstock with an external CSV file. Initially, the problem was that the imported data was sorted in "descending" order while Highcharts required it to be sorted in "ascending" order. After discovering a ...

Box Pattern with Pop-Up Modal

Check out the grid of squares I've coded below: <div class='square-container'> <div class='square'></div> <div class='square'></div> <div class='square'></div& ...

Vue project encountering issue with displayed image being bound

I am facing an issue with a component that is supposed to display an image: <template> <div> <img :src="image" /> </div> </template> <script> export default { name: 'MyComponent', ...

Framework7 initialization not triggering when page is initialized

Unable to get init function working in my Framework 7 app. I have attempted all the solutions provided in the following link: Framework7 Page Init Event Not Firing // Setting up Application var myApp = new Framework7({ animateNavBackIcon: true, ...

Is there a way to connect either of two distinct values in Angular?

Looking to assign the data with two possible values, depending on its existence. For instance, if I have a collection of TVs and I want to save the "name" value of myTVs[0] and myTVs[1]. For example: var myTVs = [ { "JapaneseTV": { ...

How to merge multiple JSON files in a directory using jq

I have a collection of approximately 100 JSON files, each containing an array with 100 simple records that I want to merge into a single file to use as static data in an application. This will help me avoid making multiple API calls to retrieve small piece ...