Is there a proven method for transforming CSV arrays into JSON files containing nodes and edges?

This is a simple example.

CSV data file :

name, source, target
John  , A ,    None
Emma  , B ,    A
Mike  , C ,    A

Theoretical JSON representation :

{
  "comment": "example code",
  "nodes": [
    {
      "name": John,
      "source" : A
    },
    {
      "name": Emma ,
      "source" : B
    },
    {
      "name": Mike , 
      "source" : C
    }
  ],
  "links": [
    {
      "source": B,
      "target": A
    },
    {
      "source": C,
      "target": A
    }
  ]
}

Visualized graph concept:

B  -> A  <-  C

The JSON format shown above is just one possibility. There are many other ways to structure the data in a JSON file.

I am looking for a tool or library that can easily convert CSV arrays into JSON files for creating JavaScript graphs.

I have multiple CSV files that I want to convert into interactive graphs using JavaScript, but first I need well-structured JSON input data. I am interested in automating the process of constructing JSON files.

Answer №1

Check out this code snippet utilizing the csvtojson library.

const csv = require('csvtojson');

const csvFilePath = 'test.csv';
var data = [];

csv().fromFile(csvFilePath)
    .on('json', (jsonObj) => {
        data.push(jsonObj);
    })
    .on('done', (error) => {
        if (error) {
            console.error(error);
        } else {
            processJSONData(data);
        }
    });

function processJSONData(data) {

    var processedData = {
        comment: "hello",
        nodes: [],
        links: []
    };

    data.forEach(function(row){

        // Check for empty or 'None' fields
        if(row.name && row.source){
            processedData.nodes.push({ name: row.name, source: row.source });
        }

        if (row.source && row.target) {
            processedData.links.push({ source: row.source, target: row.target });
        }
    });

    // Do something with the final data structure
    console.log(processedData);
}

Answer №2

Here is a technique using an advanced data processing tool called jq

If you have a file named filter.jq with the following content:

[
  split("\n")                                                    # separate string into lines
| [.[0]    | split(",")[] | gsub("[[:space:]]+";"")] as $headers # extract headers
| (.[1:][] | split(","))                                         # split data rows
| select(length>0)                                               # remove empty lines
| [   [ $headers, map(gsub("[[:space:]]+";"")) ]                 # 
    | transpose[]                                                # combine keys and values
    | {key:.[0], value:.[1]}                                     # create objects
  ] | from_entries                                               #
]
| {
    "comment":"example code",                                    # convert objects
    "nodes": map({name,source}),                                 # to desired format
    "links": map(select(.target!="None")|{source,target})        #
  }

and your data file named data looks like this:

name, source, target
John  , A ,    None
Emma  , B ,    A
Mike  , C ,    A

then when you run the command

jq -M -R -s -r -f filter.jq data    

you will get the following output:

{
  "comment": "example code",
  "nodes": [
    {
      "name": "John",
      "source": "A"
    },
    {
      "name": "Emma",
      "source": "B"
    },
    {
      "name": "Mike",
      "source": "C"
    }
  ],
  "links": [
    {
      "source": "B",
      "target": "A"
    },
    {
      "source": "C",
      "target": "A"
    }
  ]
}

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

Troubleshooting HTML/JavaScript with JSP and JSTL: iPhone only displaying the first option in select dropdown, rather than the selected option

My HTML includes a <select> element: <select id="mySelect"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> ...

Issue with Material UI dropdown not selecting value on Enter key press

I have encountered an issue with the material UI dropdown component that I am using. When I navigate through the dropdown options using arrow keys and press enter, the selected value does not get highlighted. Below is the code snippet for the dropdown: ...

Nested ng-repeat for dynamic variable rendering

I am facing an issue where I have a nested ng-repeat directive. I am attempting to create a dynamic second ng-repeat, using a key from the first one, but the current syntax is not working. Is there a different way to achieve this? Perhaps a different nota ...

The drop-down menu fails to appear when I move my cursor over it

#menu { overflow: hidden; background: #202020; } #menu ul { margin: 0px 0px 0px 0px; padding: 0px 0px; list-style: none; line-height: normal; text-align: center; } #menu li { display: inline-block; } #menu a { display: block; position: relative; padding ...

Is there a way to terminate an ongoing axios request?

I have been encountering a memory leak issue whenever my browser is redirected away from this component. To resolve this, I tried to cancel it using the cancel token, but unfortunately, it doesn't seem to be working as expected. I am puzzled as to why ...

What is the functionality of promisifyAll and what are the necessary conditions for it to operate effectively?

When it comes to promise libraries like bluebird, there is a function called promisifyAll that can convert async functions with callback patterns into promise-based functions using resolve(), reject(), or done(). But how exactly does this conversion proces ...

Leveraging the jQuery live() function to optimize heavy usage of Ajax on a website

Trying to ensure that all scripts are properly executed as content is loaded and removed from the page using jQuery load has been a challenge. The most effective approach so far has been the live function, but I have encountered difficulties in getting it ...

The clash between Traditional JavaScript and jQuery

As I pored over a textbook, I found myself stumped by an example problem. Here is the HTML code in question: $(function(){ $("#checkAll").click(function(){ $("[name=items]:checkbox").attr("checked", true); console.log("check all"); }); $("#checkNo").cl ...

What is the best way to start a jquery function within a tab that has been loaded using AJAX?

My AJAX loaded tabs are functioning correctly with the following code: <div id="tabs"> <ul> <li><a href="../about-leadership-admin-ajax/">Leadership / Admin</a></li> <li><a href="../about-sales-market ...

Tips for determining the outcome of subtracting dates

My issue involves dates formatted like this 2017-07-25 09:30:49. I need to subtract two specific times, 2017-07-25 10:30:00 and 2017-07-25 09:30:00, in order to get a result displaying the time elapsed as 1 Hour. I have been struggling to find the correct ...

Tips for updating a React state while using the history API

In an effort to simplify and stay focused on the problem, I recently wrote a brief piece of code. Within this code, there is a component containing a Dialog that plays a role in a commercial process. This Dialog allows users to input information such as no ...

Finishing up with regular expressions

I want to create an autocomplete feature for the input field on my website. For instance, when the tab key is pressed, I want the word htt to automatically become tp:// in the input value. This autocomplete should only work if the user inputs "htt" at the ...

Chartjs failing to display chart

Displayed below is the code snippet where I'm attempting to render a chart: <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js" charset="utf-8"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs ...

My goal is to transfer information from the client-side to the server-side upon the user disconnecting from a socket.io connection using Node.js

Is there a way to transmit data from the client side to the server side when a user disconnects from a socket.io connection in Node.js? I attempted creating a new event and calling it within the 'disconnect' event, but it seems impossible since t ...

Hide the element, update its content, and smoothly transition back

I am looking to add dynamic content to an element on my HTML page, with the inserted HTML transitioning smoothly from 0% to 100% opacity. HTML <div id="content"></div> CSS #content { opacity: 1; transition: opacity .5s ease-out; -moz ...

Screening strings and arrays based on multiple criteria

My code is below and I am trying to have the bot check for two specific conditions in the user's message. The message must contain "how" plus either "doing" or "bread". It works perfectly when using only "doing" but not when adding the "bread" conditi ...

What is the process for initiating a state transition?

I have created two separate components. One component uses v-navigation-drawer, while the other component contains a button that toggles the state of the v-navigation-drawer using vuex. On smaller screens, when clicking on the gray area to close the navig ...

Draggable element with a centered margin of 0 auto

Encountering an issue with jQuery UI sortable/draggable where the element being dragged, when centered using margin:0 auto, starts dragging from the left side of the container instead of the center where it is positioned. Check out this demo to see the pr ...

Issue: Unable to retrieve the property "div" as the animated object is not defined

Recently, I decided to enhance my JavaScript skills by following a tutorial on creating a dating site using the react-tinder-card component. However, during implementation, I encountered an error message: Uncaught runtime errors: ERROR can't access pr ...

React rejects the rendering of a div element

I've encountered an issue with my web application where the /tasks section is not displaying any content, even though everything else is working fine. I've double-checked my code and it seems to be identical to the other elements. import React, ...