Transform CSV data into JSON format for proper structuring

I am currently working with CSV data that includes a column 'characteristic' with three types and a 'value' column containing the numerical values for each characteristic. I am looking to restructure this data so that each characteristic becomes a separate column and its corresponding values fall directly under it.

Here is an example of the current structure: https://i.sstatic.net/3R8eh.png

And this is the desired structure: https://i.sstatic.net/9dVHK.png

I manually changed the structure in the example, but the actual table is thousands of lines long, so I am looking for a way to programmatically achieve this restructuring.

The reason for this restructuring is that I want to convert the CSV data to JSON format, where each row will look like this:

    [
      {
        "country":"afghanistan",
        "iso3":"afg",
        "first_indicator":3,
        "second_indicator":5,
        "third_indicator":3
      },
      {
        "country":"united states",
        "iso3":"usa",
        "first_indicator":8,
        "second_indicator":6,
        "third_indicator":7
      },
      {
        "country":"china",
        "iso3":"chn",
        "first_indicator":6,
        "second_indicator":0.7,
        "third_indicator":2
      }
    ]

Is there a way to automatically transform my current CSV structure (as shown in the first screenshot) into the JSON format I need, without manual intervention? I have searched extensively but have not found a solution. I am open to suggestions, but ideally, I would like to use JavaScript for this task. Thank you.

Answer №1

Here is a specialized JSFiddle that I created for your convenience, tailored to your specific needs.

JavaScript

function Country(name, short){
    this["country"] = name;
    this["iso3"] = short;
}

function findCountryByName(name) {
    for(var i = 0; i < countries.length; i++){
        var country = countries[i];
        if(country["country"] == name){
            return country;   
        }
    }
    return null;
}

var csvData = "country,shortname,characteristics,value\nafghanistan,afg,first_characteristic,3\nunited states,usa,first_characteristic,8\nchina,chn,first_characteristic,6\nafghanistan,afg,second_characteristic,5\nunited states,usa,second_characteristic,6\nchina,chn,second_characteristic,0.7\nafghanistan,afg,third_characteristic,3\nunited states,usa,third_characteristic,7\nchina,chn,third_characteristic,2"

var csvRows = csvData.split("\n");
var countries = [];

if(csvRows.length > 0){
    var headerRow = csvRows[0];
    var columns = headerRow.split(",");
    var countryIndex = columns.indexOf("country");
    var shortnameIndex = columns.indexOf("shortname");
    var characteristicsIndex = columns.indexOf("characteristics");
    var valueIndex = columns.indexOf("value");

    for(var i = 1; i < csvRows.length; i++) {
        var row = csvRows[i];
        var columns = row.split(",");

        var name = columns[countryIndex];
        var short = columns[shortnameIndex];
        var characteristic = columns[characteristicsIndex];
        var value = columns[valueIndex];

        var country = findCountryByName(name);
        if(!country){
            country = new Country(name, short);   
            countries.push(country);
        }

        country[characteristic.replace("characteristic", "indicator")] = +value;
    }
}

console.log(countries);
console.log(JSON.stringify(countries));

The resulting output provided by the code is as follows:

[{"country":"afghanistan","iso3":"afg","first_indicator":"3","second_indicator":"5","third_indicator":"3"},
{"country":"united states","iso3":"usa","first_indicator":"8","second_indicator":"6","third_indicator":"7"},
{"country":"china","iso3":"chn","first_indicator":"6","second_indicator":"0.7","third_indicator":"2"}]

Answer №2

If you're looking to transform your CSV file into a JSON format, I recommend using an internet application. Once you have the JSON data, you can easily manipulate it using Javascript to meet your specific requirements.

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

Guide on building a JSON hierarchy starting with a single parent node and several offspring nodes

My Java project involves creating a JSON object with a root node and child nodes. I have successfully implemented this, but now I need to add more children to the existing child nodes under the root node. Unfortunately, I am facing challenges in achieving ...

Could you provide some advice for creating a Single Page website?

I am working on a simple HTML setup with various elements such as a navbar and content blocks. <html> <head> <title>My HTML5 App</title> <meta charset="UTF-8"> <meta name="viewport" content="wid ...

The Bootstrap datepicker functions properly when used in plain HTML, but encounters issues when implemented within the .html()

Using HTML: <input class="m-ctrl-medium date-picker" size="16" type="text" id='lateETD1' name="dateRecv" value=""/> Not working with script: var ETD = $("#ETD"); ETD.html("<input class='m-ctrl-medium date-picker' id='la ...

Encountering an issue with receiving "undefined" values while utilizing WordPress post metadata in AngularJS

Utilizing the Wordpress REST API v2 to fetch data from my functional Wordpress website to an AngularJS application. Everything is functioning properly, however when I attempt to access post meta such as "_ait-item_item-data", it returns an error stating "u ...

What are the steps to storing numerical inputs as variables using jQuery and then using them to perform calculations in order to update the input numbers

Currently, I am in the process of creating a BMI calculator using HTML and jQuery. <form id="bmiCalculator"> <fieldset> <legend>BMI Calculator:</legend> <p> <label>Height: ...

When employing useEffect, clearInterval cannot halt the execution of SetInterval

My attempt to create a function that initiates a countdown when the isPlaying variable is true and stops when it's false has not been successful. Instead of working as intended, it starts multiple intervals concurrently. The value of isPlaying changes ...

What is the best way to utilize the history prop in conjunction with other props?

I am currently using react-router-dom along with react. My goal is to include additional props along with the history prop import React from 'react'; function MyComponent({ history }) { function redirect() { history.push('/path&ap ...

ng-model fails to synchronize with HTML

When I click on ng-click, the model changes but the HTML remains the same... HTML <p>Reserved:<span>{{seatsInfo}}</span></p> <div ng-click="change()">change</div> JavaScript $scope.seatsInfo = 20; $scope.change = fu ...

Converting PPT files to PDF or PNG using Node.js

Are there any options available for converting ppt files to pdf or png without relying on specific operating system dependencies? I need to convert a ppt file to png, but all the current packages I have tried require tools like LibreOffice or ImageMagick ...

What steps can be taken to determine the cause of an abrupt closure of a websocket client?

My browser game utilizes the ws module. However, there seems to be an issue where connections from distant computers randomly close while playing the game. The screen freezes when this happens, but interestingly, I do not encounter this problem when testin ...

Cancel all asynchronous requests

On my webpage, I trigger 15 ajax requests and have a button to cancel all pending ajax requests. According to the documentation, the abort() function terminates the request if it has already been sent. However, even after clicking the cancel button, I sti ...

Using plain JavaScript, adding an element to an array by pushing the value of a string variable in an index position rather than pushing the

I have the following JavaScript code snippet: let array = []; const datas = [ 'name1', 'name2', 'name3', ]; async function getData() { datas.forEach((data) => { let myData = data.name; if(!array.include ...

Why is the result of this specific JavaScript code a string?

let x = 2, y = x = typeof y; console.log(x); // >> 'string' Could you explain why the value of x ends up being a string in this code snippet? ...

Troubleshooting the Hover Effect of Buttons in Next.js when Using Tailwind CSS for Dynamic Color Changes

Encountering a problem with button hover functionality in a Next.js component using Tailwind CSS. The objective is to alter the button's background color dynamically on hover based on a color value stored in the component's state. This code func ...

What sets apart assigning a React ref using a callback versus setting it directly?

Is there a practical difference between directly setting a ref and setting it via a callback with the element as an argument? The functionality remains the same, but I am curious about any potential distinctions. Consider this react hook component: const ...

What is the best way to emphasize colors in search results?

Is it possible to assist in highlighting the searched words in yellow? Below is an example of code that filters words from the displayed data from a JSON feed URL. angular.module('sample', []). controller('sampleController', [' ...

Fetching Results from Promise

Repeatedly, this question has been asked in various forms but I still do not understand: I have a resolved promise with a value. When I console.log this object, everything appears to be functioning correctly. I can see exactly what I want to see. My setu ...

Guide to rearranging the sequence of items in a selected jQuery collection

I have created a JavaScript filter that targets elements with the class .single: There are numerous divs with the class .single, each containing multiple text elements. The filter has already been set up to hide all .single elements that do not contain an ...

Show only the image source (img src) and do not display the audio and video sources using jQuery

In my code, I need the following conditions to be met: when an image is posted from the backend, the video and audio sources should automatically hide; when a video is posted, the image and audio sources should hide; and when an audio file is posted, the v ...

Accessing array values depending on DOM response

Generate a string from selected DOM elements I have an object that contains months and their corresponding index numbers (not dates) monthList = {"jan" : "1", "feb" : "2". etc: etc} The user can input values like jan or jan,feb,march and I need to return ...