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

Executing Datalist's Delete Command through Page Methods Implementation

Recently, I came across an issue with my DataList and Update Panel on my webpage. I noticed a significant delay in response time after incorporating the Update panels... intrigued, I delved deeper into this phenomenon and found some interesting insights in ...

An unanticipated issue has arisen with the Alert Open Error. The command "browser.switchTo().alert().accept();" functions properly in Firefox, but encounters difficulties in Chrome while executing via Jenkins

Seeking assistance on how to resolve a specific error encountered in the Chrome browser while using Protractor. https://i.stack.imgur.com/7Fm4l.png The error message reads as follows: "UnexpectedAlertOpenError: unexpected alert open: {Alert text : There a ...

Tips for maximizing page layout efficiency without compromising on element visibility

What is occurring https://i.stack.imgur.com/Agjw6.gif The use of .hide() and .fadeIn(200) is resulting in a jittery effect that I would like to avoid. Desired Outcome When the user hovers over the menu icon, the menu icon should vanish the text "Pr ...

A guide on achieving server-side rendering in React despite facing various conflicts with React Router versions

I encountered an error while trying to implement server-side rendering with React and react-router-dom. The error message You should not use Switch outside a Router has me puzzled. I suspect it might be due to a version conflict, but I'm searching for ...

Tips to prevent the return of undefined when a condition is not satisfied

I'm currently working on a react app and I have an array of objects (items) that I want to iterate over in order to display each object based on its index. I am using useState to set the index, which is updated when the user clicks a button. const ...

PHP is struggling to interpret the JSON object

I am struggling to pass the username and password to a PHP script and verify them in the database. To achieve this, I utilize the following client-side script to create a JSON object and send it to the PHP file. var myobj = {}; myobj["usrname"]= $( "#cust ...

Error in THREE.js: The function material.onBeforeRender is not defined

Can someone assist me with an error I'm encountering while trying to run my code in Three.js? The error message reads as follows: three.js:19528 Uncaught TypeError: material.onBeforeRender is not a function at renderObject (three.js:19528) at ...

Playing around with Scala to verify JSON data containing IP addresses

Just dipping my toes into the world of Play and Scala, I'm attempting to validate a JSON payload in a POST request within a Play Controller. The code I've managed to put together thus far works fine without input validation, but now I'm hitt ...

What is the best way to change a string that represents an array into an actual array?

Experimenting with something new... Imagine I have the following HTML code: <div id="helloworld" call="chart" width="350" height="200" value="[[4, 8, 1, 88, 21],[45, 2, 67, 11, 9],[33, 4, 63, 4, 1]]" label="['test1', ...

What is the best way to tidy up messy JSON data filled with newline characters, extra spaces, and improper formatting using Python?

I'm currently working on a project where I am extracting data from pcpp in JSON format and my objective is to save this information into a file. from pcpartpicker import API import json api = API("in") categories = list(api.supported_parts) parts = ...

Is there a way to access the value of a variable in Express that is stored in a different file?

Looking for a way to fetch the value of a variable that is located inside app.use? chatbot.js: const express = require('express'); const app = express.Router(); app.use(['/chat', '/chatbot'], (req, res, next) => { const ...

Displaying AJAX data in a table format, showcasing 10 rows of information

I am currently working on an ajax function that retrieves data from a database based on the entered information. My goal is to display this information in a table with the following format: System Id | Last Name | First Name | Middle Name | Address Below ...

Error: The property 'slice' cannot be read from an undefined value

I am currently working on a prototype recipe app called Forkify, which is being developed using Javascript, NPM, Babel, and Webpack. In this project, I am utilizing a custom API. API URL : forkify-api.herokuapp.com TO SEARCH RESULT This API returns a l ...

Template not rendering array data correctly in Meteor

Here is an example of the array structure: var myarray = [ device1: [ name:device1 , variables: [ variable1: [ name: variable1, unit: "a unit", ...

Why Does React Material-UI Switch Styling Keep Changing Sporadically?

Currently, I am trying to integrate a switch component from MUI into my code. Strangely enough, upon the initial page load, the switch appears exactly as it should - identical to the one displayed on the MUI site. However, upon reloading the page, it under ...

React TypeScript with ForwardRef feature is causing an error: Property 'ref' is not found in type 'IntrinsicAttributes'

After spending a considerable amount of time grappling with typings and forwardRefs in React and TypeScript, I am really hoping someone can help clarify things for me. I am currently working on a DataList component that consists of three main parts: A Co ...

Expanding accordion functionality and implementing JavaScript events within a content template

Delving quickly into the code, below you will find the asp.net markup for an accordion that serves as a container for topic headlines as headers for each panel. The contents of these panels are comments to be moderated. <ajaxToolkit:Accordion runat="se ...

Utilizing lazy evaluation, multiple functions are triggered by ng-click in succession

Successfully disabled ngClick on an element when the scope variable (notInProgress) is set to true as shown below: <a data-ng-click="notInProgress || $ctrl.setTab('renewal');</a> Now, I want to include additional functions to be execut ...

Discover the process of incorporating secondary links into your dabeng organizational chart!

I need to incorporate dotted lines on this chart, such as connecting leaf level nodes with middle level nodes. import OrgChart from '../js/orgchart.min.js'; document.addEventListener('DOMContentLoaded', function () { Mock.mock(&apo ...

What could be causing this JavaScript to output undefined?

const urls = [ "http://x.com", "http://y.com", "http://z.com", ]; for (let j=0; j<urls.length; j++) { setTimeout(function() { console.log(urls[j]); }, 3000); } I'm inserting this code snippe ...