Transforming CSV files into JSON format using d3.js

I'm encountering an issue when attempting to convert CSV to JSON. The following is the snippet of code I am using for the conversion:

d3.csv("http://localhost:8080/Sample/flight.csv", function(flights) {           
                //alert(flights);
              var linksByOrigin = {},
                  countByAirport = {},
                  locationByAirport = {},
                  positions = [];

              var arc = d3.geo.greatArc()
              .source(function(d) { return locationByAirport[d.source]; })
              .target(function(d) { return locationByAirport[d.target]; }); 

              //reading from csv
                flights.forEach(function(flight) {
                var origin = flight.origin,
                    destination = flight.destination,
                    links = linksByOrigin[origin] || (linksByOrigin[origin] = []);
                links.push({source: origin, target: destination});
                countByAirport[origin] = (countByAirport[origin] || 0) + 1;
                countByAirport[destination] = (countByAirport[destination] || 0) + 1;
              });   

});

to

d3.json("http://localhost:8080/Sample/flight.json", function(flights) {             
                //alert(flights);
              var linksByOrigin = {},
                  countByAirport = {},
                  locationByAirport = {},
                  positions = [];

              var arc = d3.geo.greatArc()
              .source(function(d) { return locationByAirport[d.source]; })
              .target(function(d) { return locationByAirport[d.target]; }); 

              var flights = flights.flights;
              alert("flights"+flights.length);
           for(var i = 0; i < flights.length; i++)    {    
               alert("origin"+flights[i].origin+"dest"+flights[i].destination);
                 var origin = flights[i].origin;
            var  destination = flights[i].destination;
          alert("origin"+origin+"dest"+destination)
                var links = linksByOrigin[origin] || (linksByOrigin[origin] = []);
                links.push({source: origin , target: destination});
                countByAirport[origin] = (countByAirport[origin] || 0) + 1;
                countByAirport[destination] = (countByAirport[destination] || 0) + 1;   
           }
});

When I use the json code, I encounter the error

19:15:41.950 TypeError: _ is undefined1 d3.v2.js:1982:10
. Can someone please guide me on what mistake I might be making during the conversion process?

Answer №1

Without seeing your specific json object, it's difficult to provide a definitive answer. However, assuming that your csv file returns an array of objects like this:

[{origin: 'origin string', destination: 'destination string'} ... ]

And if your json structure is similar to the following:

{flights: [{origin: 'origin string', destination: 'destination string'}, ...]}

Then your code should function as expected. If your json data follows a different format, feel free to share sample csv and json files for a more precise solution.

It's possible that the issue lies in the absence of a "flights" variable within your json file, leading to the error you encountered.

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

How can I store the content of a meta tag in a JavaScript variable?

Similar Question: How can I extract data from a meta tag using JavaScript? I have a meta tag that can be customized with content on a specific page, and I'm looking to retrieve this content as a variable in JavaScript. ...

I require the output to be saved in a txt file rather than a JSON object

Can this code be modified to output its results to a text file rather than a JSON/curl object? We are troubleshooting a specific sku and need to view the long query's output that comes before this snippet: foreach($group_sets AS $group_set) { $b ...

Executing a function when a user chooses to exit a webpage using the @HostListener('window:beforeunload') method

Utilizing @HostListener('window:beforeunload') allows me to detect when a user navigates away from the page, prompting a dialog window to open. I wish for an event to be triggered or a method to be executed if the user chooses to leave the page. ...

Having difficulty retrieving information from Redux store

In my project, I utilize the Redux store to manage data. Through Redux-DevTools, I can observe that initially the data is null but upon refreshing the page, the data successfully populates the store. However, when attempting to retrieve this data within on ...

Utilize the Action method selector for distinguishing between Ajax and non-ajax requests, rather than depending on if(Request.isAjaxRequest)?条件

I recently started working through a book titled 'Asp.Net MVC4 in Action'. At one point, the book suggests using an action method selector instead of relying on if statements to check if a request is Ajax. This involves creating a custom class ca ...

Transforming a JSONArray into a regular Array

I transformed a regular array of user-defined objects into a JSON Array. Now I'm wondering how to convert the JSONArray back to a normal array of the same type. In order to accomplish this, I am utilizing Json for shared preference in an Android appli ...

Create a gulp task within a callback function that is initiated by calling the filesystem.readdir

When attempting to read the name of the first folder from a directory, and then defining gulp tasks based on that folder, I am encountering an issue. Specifically, after defining a task inside the callback function, the tasks do not get properly defined. T ...

Customize the CSS for MaterialUI's TablePagination's MenuItem

Having trouble figuring out how to override CSS for the child component MenuItem within TablePagination? Check out this link for more information: https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/TablePagination/TablePagination.j ...

What is the procedure for passing arguments to Google signIn in a NextJS backend?

I am currently working on implementing a role-based Google sign-in feature in a Next.js 13 app using next-auth. This setup involves calling two different tables to create users based on their assigned roles. For the database, I am utilizing mongodb/mongoo ...

Why isn't my SCO considered complete?

My SCO is very basic, with an empty html page. I am utilizing the pipwerks scorm api wrapper in Chrome dev tools to establish a connection to the LMS, set cmi.completion_status to "completed", and cmi.success_status to "failed" (as outlined in the scorm ru ...

`Creating the perfect bar``

Currently working on my resume using Angular and I am interested in incorporating a visual representation of my skill level in specific subjects. Came across something that caught my eye here: The challenge now is figuring out what exactly to search for i ...

What is the best way to incorporate a mute/unmute button into this automatically playing audio?

Seeking assistance in adding a mute button for the background sound on my website. Can anyone provide guidance on how to achieve this? Below is the HTML code responsible for playing the sound: <audio id="sound" autoplay="autoplay" ...

Determining when a checkbox changes state using HTML and JavaScript

My main objective is to display divX2 when the checkbox for x2 is checked, either by directly clicking on x2 or by clicking on the "Check All" checkbox. The functionality works as intended when the checkbox for x2 is clicked, but it fails to work when the ...

``Is there a way to access the $attrs data of child DOM elements from within a controller?

Imagine having a controller and multiple children DOMs each with their unique data attributes. <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> < ...

Utilizing PHP and AJAX to Extract Information from a MySQL Database

My goal is to fetch data from a MySQL database hosted on a webserver and display it in an HTML table. I've been following an example on W3Schools, but I'm facing issues retrieving the data successfully. Here is the source code: (HTML) <html& ...

Utilizing eval properly in JavaScript

One method I am using is to load a different audio file by clicking on different texts within a web page. The jQuery function I have implemented for this purpose is as follows: var audio = document.createElement('audio'); $(".text_sample ...

Changes to attributes of an HTML tag cannot be made by jQuery code during an AJAX call

Could someone help me figure out why this jQuery code is not functioning properly? I have already tested it outside the $(document).ready block with no success. Note: The unusual "{{ }}" and "{% %}" syntax is typically used in Django. jQuery $(document) ...

Inject the content loaded from the server into a div element, and insert that div at the

I am trying to insert the div(#loadmore) element inside the div(#boxchatting) element when the content from "result.php" is loaded into div(#boxchatting). Here is the code I used: $('#loadmore').prependTo('#boxchatting'); $('#boxc ...

Extracting a subclass from an array

Currently, I am delving into the world of coding as part of a project I'm working on. Here is an excerpt from my JavaScript code that interacts with Google Maps API: for (i = 0; i < results.length; i++) { console.log("Formatted Address: "+ re ...

Customize Material-UI icons dynamically by changing their props in an array

I am looking to change props (color, size) for multiple icons in an array using Material-UI v4: const ICONS_ARRAY: React.ReactNode[] = [ <AlertCircleCheckOutline />, <AppleSafari />, <MotionPlay />, <AppleKeyboardCommand />, <Fil ...