Using JavaScript and the PapaParse library, you can easily convert CSV data into an array

My current task involves using Papaparse to convert a csv file into a json object.

The API requires the data to be structured like this:

"data": [
        {
            "id": 1,
            "nombre": "AGUASBLANCAS-AGB",
            "descripcion": "-",
            "it_unidad_generadora": 0
        },
        {
            "id": 425,
            "nombre": "AGUASBLANCAS-AGBQ",
            "descripcion": "-",
            "it_unidad_generadora": 403
        }
    ]

However, after using Papaparse, the csv gets converted into an array of arrays representing each row like this:

"data":  [
    0: ["ID", "NOMBRE", "DESCRIPCIÓN", "IT UNIDAD GENERADORA"]
    1: ["1", "AGUASBLANCAS-AGB", "-", "0"]
    2: ["425", "AGUASBLANCAS-AGBQ", "-", "403"]
    ]

I am looking for a way to transform this into a JSON array of objects using Papaparse, rather than an array of arrays representing each row. Can anyone provide guidance on achieving this?

Answer №1

For more information, check out the documentation at:

To convert the result into an array of objects, all you need to do is set header: true in the options.

const parsedData = Papa.parse(data, { header: true });

Answer №2

Try out a different library instead of Papaparse, such as https://www.npmjs.com/package/csvtojson

This alternative library has garnered impressive download numbers and might be just what you need for handling your data.

Answer №3

Here is how I tackled the problem:

I employed Papa.parse(event.target.files[0], {complete: async results => {
    let keys = results.data[0];
    // My goal was to eliminate special characters, spaces, and more
    keys = results.data[0].map(v => v.toLowerCase().replace(/ /g,"_").normalize('NFD').replace(/[\u0300-\u036f]/g,""));

    let values = results.data.slice(1);
    let objects = values.map(array => {
      let object = {};
      keys.forEach((key, i) => object[key] = array[i]);
      return object;
    });
    // I then proceeded to call my API with the data successfully
    await uploadCSV(type, objects);
  }
});

Although it wasn't related to Papaparse configuration, I used JavaScript to generate objects with specific keys extracted from the first row of the array.

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

Discover if every single image contains a specific class

HTML : <div class="regform"><input id="username" type="text" name="username" placeholder="Username" required><h3 class="check"><img src=''/></h3></div> <div class="regform"><input id="password" type=" ...

Encounter a problem while trying to access JSON data through HTTPGet on Android

My expertise lies in developing Android applications that can retrieve JSON data from a specified URL: I am currently working on displaying detailed information about vendors, and to achieve this, I pass the parameter "Lumineux" from my Android applicatio ...

Node.js server crashes upon automatic startup but remains stable when started manually

Currently, I am using Node.js and Socket.io to power an online chat feature. To manage the server, I have created a configuration file located at: /etc/init/example.conf The contents of this file are as follows: start on startup exec forever start /var/ ...

unable to verify the JSON request in PHP

Working with an API involves sending a request and receiving a JSON response on the provided link. In order to verify the received request, the following code snippet was written: if(isset($_REQUEST)){ file_put_contents('file.txt', json_encod ...

Loading select list options asynchronously

I am working on extracting data related to Municipality names, ZipCodes, and more from a public service provider called DAWA using AJAX. Initially, I faced an issue with retrieving the data until I made the transfer asynchronous; hence, the function ajaxGe ...

The Journey of React Native Routing

When building my React Native application, I encountered a challenge with creating a Footer and Tab menu that should only be displayed on certain screens. If I define them within the NavigationContainer, they apply to all screens uniformly. How can I sep ...

Is it possible to use a Proxy-object instead of just an index when changing tabs in material-ui/Tabs?

Using material-ui tabs, I have a function component called OvertimesReport with Fixed Tabs and Full width tabs panel: const TabContainer = ({children, dir}) => ( <Typography component="div" dir={dir} style={{padding: 8 * 3}}> {children} & ...

The AngularJS element fails to display on the screen

I am currently learning AngularJS and I am struggling to understand how components are linked to the view in the tutorial. I have created a component that is quite similar: angular.module('phonecatApp').component('nameList', { temp ...

Attempting to utilize JSON.Stringify on Scripting.Dictionary objects will result in failure

In my current ASP classic project, I have integrated the JScript JSON class available at this link. This class can interact with both VBScript and JScript, closely resembling the code provided on json.org. However, due to team manager's requirement, I ...

"Encountered an error: AngularJS is unable to read the property 'push' as it is

I'm attempting to generate an array using data retrieved from an API. However, I continue to encounter an error message stating cannot read property 'push' of undefined in Javascript. Could someone please guide me on how to resolve this iss ...

"Creating a new element caused the inline-block display to malfunction

Can someone explain why the createElement function is not maintaining inline-block whitespace between elements? Example problem First rectangle shows normal html string concatenation: var htmlString = '<div class='inline-block'...>&l ...

Using the spread operator in React to distribute JSX elements within a map function

I am struggling with mapping over an array within another array to create a Picker and am having difficulty returning JSX elements instead of an array of JSX elements. Here is the code example: {modelA.map((mA) => { const pickerItems = mA.modelB.m ...

Learn the process of filtering an array using another array

I have a collection of items set up in the following format. items = [ { id: 1, status : "Active" // Other fields tags : [{val: 'IGM', color: 'light-success' }, {val: 'Gated Out', colo ...

AngularJS (ui-mask) provides a valid input mask feature

i encountered an issue while trying to create an input mask using ui-mask in AngularJs. I want the textarea to turn green when the entered string is correct. However, in my case, the textarea starts off green and then turns red when a word is typed until t ...

Add a file to your Google Drive by utilizing AJAX with Google Apps Script

Currently, I am working on a code to upload an image file to Google Drive using app script. I have encountered an issue where I am unable to retrieve the file from the request.parameters. I attempted to use formData as well, but it did not resolve the pro ...

Exploring ways to replicate the functionality of Gmail's Contact manager

Looking to develop a contact manager similar to Gmail's interface. While I have a basic understanding of AJAX and some experience with jQuery, my JavaScript skills are limited. Any suggestions for books or blogs to improve them would be welcome. Tha ...

What is the process for updating the combination selector for each product within a specific category in PrestaShop 1.7?

We have a range of products in a specific category, each offering multiple pack sizes with varying prices (e.g. 1, 3, 5, 10, 25, 50, 100). EDIT: The homepage features these products displayed using an owl-carousel within a div element: When a customer se ...

Tips for displaying specific information using Javascript depending on the input value of an HTML form

I am working on an HTML form that includes a dropdown list with four different names to choose from. window.onload = function(){ document.getElementById("submit").onclick = displaySelectedStudent; } function displaySelectedStu ...

What could be causing my fetch() function to send a JSON body that is empty?

I've been struggling with sending JSON data using fetch as the backend keeps receiving an empty object. In my Client JS code, I have the following: const user = "company1"; const username = "muneeb"; const data = {user, username}; fetch("http://127. ...

Is there a way to use fetch() to automatically redirect a user after logging in?

I'm currently working on a node.js application using express, and I am in the process of creating a login form for my users. I want to include a Javascript file that utilizes fetch() to send a POST request to my API for user authentication. However, I ...