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

The function Expo.Fingerprint.isEnrolledAsync will provide an output that includes information about fingerprint

Attempting to incorporate fingerprint authentication into my react native app. Utilized Expo SDK for this purpose. Although the Expo.Fingerprint.authenticateAsync() method claims to return a boolean, it actually returns an object when examined closely. E ...

ngSanitize continues to present plain text rather than rendering HTML code

When working with AngularJS scope, I encountered the need to display certain items as HTML. After some research, I realized that integrating ngSanitize was necessary for this functionality. Here is how I implemented it in my app: <script src="Scripts/a ...

Bringing in a JavaScript file into a Svelte component

Today, I stumbled upon Svelte and I am really intrigued by the concept. However, I encountered an issue while attempting to import a small helper.js file. No matter what I try, whenever I reference the class, I receive the error: ReferenceError: Helper ...

Converting DataSet to JSON using ServiceStack.Text

I'm facing an issue with serializing a dataset to JSON using ServiceStack.Text (from Nuget.org). I'm currently working with the version 4.0.50 and VS 2015. The error message that keeps popping up is: Process is terminated due to StackOverflowE ...

Exports for Express Router Module/Functions

I am currently working on exporting a function and an express router from the same file. The function is intended to verify certificates, while the route is meant to be mounted on my main class for other routes to use. I want to encapsulate both functional ...

Display a loading bar or prevent any user interface actions until the server has finished generating the file

I am currently developing a force directed layout using d3.js on data retrieved from an MS SQL server database. I'm creating the json file with a python script and running it on a local server using python -m SimpleHTTPServer. My goal is to establish ...

Decoding information from Onedrive's REST API

I am currently working on retrieving information about the contents of a folder from OneDrive's server. The data structure I am dealing with is as follows: { "data": [ { "id": "folder.xxxx", "from": { "name": "j ...

What is the best approach to dynamically enable or disable a button depending on the state of multiple checkboxes in React.js?

Incorporated within a page is a component responsible for displaying multiple checkboxes and toggles. Located at the bottom of this component is a button labeled confirm, designed to save modifications and initiate a backend update request. A new functio ...

Executing a PHP script after successful execution of another script

tag, I am encountering the following script: Two minor issues: With the button being disabled after a click, it wont allow to click again if for instance an error is returned as shown above. It should only disable it after the input has been released $fo ...

Enhance your user experience with real-time autocomplete using AJAX to automatically fill in input

My autocomplete script seems to be causing an issue: When I search for "siegg," the results are displayed in the textbox, but I only want certain information to show. This is my desired outcome: Below is the Javascript code I am using: $("#place_Regist ...

BottomNavigation wrapping React Router is failing to load the updated component

I'm struggling to understand why I can't seem to load the DMO page from a BottomNavigation component. Navigating to "/dom" works fine, but clicking the buttons doesn't do anything. The initial "/" loads perfectly. Any ide ...

Prevent the sender from receiving notifications from Firestore

Data is transmitted to firestore by the sender firestore saves the data firestore shares the data with all connected clients, sender included Is there a method for the sender to not receive the notification? OR If the sender does get the notification, is ...

Exporting a object in Angular2 Using TypeScript

I've been working on a small Angular2 application using Typescript and things have been going smoothly so far. My goal is to utilize a file called config that contains all the necessary settings for the application. Here's the file in question: ...

angular click triggers the following content

How can I make the following content appear when clicked? I have a list of content that displays up to 20 items, but I want to show the rest when clicked. I have created the nextMovieList method for this purpose. import { Component, OnInit } from ' ...

Angular sing ng-view to load images from a file

I am developing a single page app (index.html) with the following relevant sections: <!DOCTYPE html> <html> <head> <base href="/mi_ui/"> <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css"> <script s ...

Exploring the intersection of JavaScript and PostgreSQL: Leveraging timezones and timestamps

I'm a bit confused about how to properly use timestamps. For example, when a user creates an article, they can choose a PublishDate, and the system also automatically stores a CreateDate. a. Should I make both PublishDate and CreateDate timestamps wi ...

Tips for accessing the JSON file containing Spark driver metrics:

After following the monitoring guide at , I tried configuring the metricsservlet but found the documentation to be lacking in useful information. According to the commons in metrics.properties: "5. MetricsServlet is added by default as a sink in master, ...

Enhancing Javascript functionality with additional on.change customization opportunities

My website currently has a dynamic AJAX script that updates a table based on the selection from a dropdown menu with the ID of [id="afl_player_ID"]. However, I am looking to extend this functionality so that the same script runs when either [id="afl_playe ...

Looking for assistance with deleting a child element in an XML file using PHP

I need help figuring out how to delete a child from my jobs.xml file with a PHP script. My jobs.xml file looks like this: <jobs> <event jobid="1"> <title>jobtitle</title> <desc>description</desc> &l ...

Converting a List of Strings to a JSON String

Is there a way to transform a List into a Json String? I've successfully done it in the opposite direction, but struggling with this method. Addtionally, I'm unsure how to define the specific key names. ...