Transforming a CSV document into a JSON format in order to generate a hierarchical tree structure for constructing a D3 categorical tree diagram

I have a CSV file that is structured like this:

"","Sequence","Paths","sequence_length"
"1","Social -> Social -> Social -> Social -> Social -> Social -> Social -> Social",29,8
"2","Social -> Social -> Social -> Social -> Social -> Social -> Social",30,7
"3","Social -> Social -> Social -> Social -> Social -> Social",40,6
"4","Social -> Social -> Social -> Social -> Social",71,5
"5","Social -> Social -> Social -> Social",156,4
"6","Social -> Social -> Social",273,3
"7","Social -> Social -> SEO",40,3
"8","Social -> Social",729,2
"9","Social -> SEO -> Social",51,3
"10","Social -> SEO",180,2
"11","Social -> SEM",56,2

My goal is to transform this data into a JSON tree structure as shown below:

{
"name": "Social",
"children": [{
    "name": "Social",
    "children": [{
        "name": "Social",
        "children": [{
            "name": "Social",
            "children": [{
                "name": "Social",
                "children": [{
                    "name": "Social",
                    "children": [{
                        "name": "Social",
                        "children": [{
                            "name": "Social",
                            "Path": 29
                        }]
                    }]
                }]
            }]
        }]
    }]
}]
}

Each touchpoint represented by 'Social' in the CSV file signifies a child node of the previous one, with the number of paths being added to the final node.

To achieve this, I am splitting the 'Social' elements into an array like this:

data.forEach(function(d){
var x =  d.Sequence.split(' -> ');

If anyone could assist me with parsing this information into JSON format, it would be greatly appreciated. Thank you!

Answer №1

I completed the task for only the first row in the csv file, similar to the example you provided. I believe it achieves the desired outcome.

Simply create an array of items and pass each one through the parseItem function. Note: the final result is an array, not an object.

Although not necessary, I implemented it as a recursive function.

The .innerHTML code is purely for display purposes. Feel free to remove those lines if you prefer.

You can continue from here, correct?

<div id="log"></div>
<hr/>
<div id="result"></div>
<script>
    var myitem = ["1", "Social -> Social -> Social -> Social -> Social -> Social -> Social -> Social", 29, 8];

    function parseItem(item) {
        // var id = item[0];
        var paths = item[1];
        var value = item[2];
        // var length =  item[3];
        var splitPath = paths.split(' -> ');

        var threeDpath = path2tree(splitPath, value);
        return threeDpath;

    }

    // recursive function
    function path2tree(paths, value) {
        // for testing and trying to understand what happens
        document.getElementById('log').innerHTML += JSON.stringify(paths) + '<br/>';

        if (paths.length == 1) { // this will only be true the last time
            return [{
                "name": paths[0],
                "Path": value
            }];
        } else {
            // splice paths[0], send the rest to the recursive function
            var path = paths.splice(0, 1);
            return [{
                "name": path[0],
                "children": path2tree(paths, value)
            }];
        }
    }

    window.onload = function() {
        var threeDpath = parseItem(myitem);
        document.getElementById('result').innerHTML = JSON.stringify(threeDpath);
    }
</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

Having difficulty generating a Meteor.js helper using a parse.com query

Utilizing my meteor application, I fetch and display data from Parse.com. Initially, I integrated the parse.com javascript query directly into the template's rendered function, which was successful. Now, I aim to utilize the Parse.com query in a help ...

Can you create a stroke that is consistently the same width as the container BoxElement?

Utilizing a BoxElement provided by the blessed library, I am showcasing chat history. New sentences are inserted using pushLine. To enhance readability, days are separated by lines (which are added using pushLine). The width of each line matches that of t ...

Guide for using two Async Pipe functions in Angular 7

Two different functions are in place to check a specific condition, and the requirement is for both of them to be true simultaneously. How can *ngIf be utilized to achieve this? Currently, setting just one of them works, but the aim is to have both. HTML ...

Strategies for extracting data from multiple Textareas in React

I am facing an issue with a form that contains multiple textarea elements (specifically 3). The problem is that when I type in one textarea, the content is automatically filled and updated in the other textareas as well. This behavior is not desired. I h ...

Trigger a drop-down list in React when typing a specific character, like {{ or @, in an input field

Is there a way in React.js to display a list or dropdown when a user types a certain character like '@' or '{{ }}' in the input text area? The user should be able to select an option from this list and have it inserted into the text are ...

What could be the reason behind Typescript's unexpected behavior when handling the severity prop in Material UI Alerts?

Trying to integrate Typescript into my react project and encountering a particular error: Type 'string' is not assignable to type 'Color | undefined'. The issue arises when I have the following setup... const foo = {stuff:"succes ...

Putting a Pause on CSS Transition using jQuery

I am attempting to delay a CSS transition for an element by using a delay function, with an additional 0.2s applied to make it slide 0.2s later than the initial delay of the main wrapper. I am applying a class to give it a transition effect to slide from r ...

Server with minimal setup requirements

While developing my Angular projects, I rely on lite server. This tool utilizes BrowserSync for tasks such as serving the site to localhost and enabling live reload functionality. In my project's root directory, there is a configuration file named bs ...

What steps should I follow to ensure that the processData function waits for the data returned by the getData function in Angular?

After calling the getData function, each object is stored in an array and returned. Now I need the processData function to await these results from getData and then further process them. However, when I try to console.log(cleaningData), I don't see an ...

Decoding the `this` Mystery in VueJS

Recently, I decided to delve into the world of VueJS starting from square one. Following their official guide has been a helpful resource, but I've hit a roadblock at this section. One particular example in the guide caught my attention... var app5 = ...

The margin and width of a div element with the position set to fixed and display set to table-cell are not rendering correctly

Is there a way to keep my .nav-container position: fixed; without creating a gap between it and the .page-content at certain window widths? When I set the position to fixed, a small white line appears between the red background of the .nav-container and th ...

Exploring the possibilities of ReactJS and the sleek design of

How can I alter the background color of a RaisedButton without having the CSS class name appear in the autogenerated div? Here is the button: <RaisedButton className="access-login" label="Acceder" type="submit"/> This is the specified CSS: .acces ...

React components do not re-render when the context value changes

The issue with React not re-rendering when the context value changes persists I am using tailwindcss, React(v18.2.0), and vite(3.2.4). I have already attempted i want that clicking on TodoItem should change the completed value in the todo using React con ...

The difference between importing CSS in JavaScript and importing it directly in CSS lies in the way

Hello there, I am just starting out with web development and learning about Vue.js. In Vue 3, the recommended way to import CSS files from different packages is as follows: Method 1: Import directly in app.js //app.js import '../css/app.css'; i ...

utilizing the .on method for dynamically inserted elements

I have a code snippet that triggers an AJAX request to another script and adds new <li> elements every time the "more" button is clicked. The code I am using is as follows: $(function(){ $('.more').on("click",function(){ var ID = $(th ...

How to Animate an Object's Rotation Gently using React Three Fiber App and Use Cannon Library?

I am currently working on a project to create a Tetris-like game using React app, react-three-fiber, and use-cannon. I would like to implement a feature where objects/meshes rotate smoothly when clicked. How can I achieve this? Here is the code for the ob ...

Unable to properly load the Kendo Tree View based on the selected option from the combo box in the Kendo UI framework

I am encountering an issue where the Kendo treeview is not populating with different values based on a selection from the Kendo combo box. I have created a JSFiddle to showcase this problem. http://jsfiddle.net/UniqueID123/sample In the scenario provided ...

Emulate a link click using key input

Hey there! I have this link example: <a href"http://google.es">Link</a> I'm wondering if it's possible to use JavaScript or a similar tool so that when I press a specific key, like the number 5 on the keyboard, it acts as if I click ...

Prevent the bootstrap dropdown menu from closing when encountering a login error during form validation using ajax and codeigniter

I encountered an issue with my dropdown menu login that utilizes bootstrap ajax and codeigniter. When I attempt to submit the form and there is an error, I have to click multiple times before the error message appears because the dropdown menu keeps closin ...

Unable to integrate bower with gulp for automation

I am trying to get gulp to run the installation of all files listed in my bower.json. However, despite writing the code below, it is not working and I'm not seeing any errors. What could be causing this issue? var gulp = require("gulp"); var bower = ...