Is there a way to transform data from a CSV format to a JSON format?

I've written the code to fetch data from a device in CSV format. Here are some sample data values:

1,1.635946,1.636609,1.640240,1.636091

2,1.642825,1.640267,1.639013,1.636568

3,1.636835,1.636022,1.637664,1.637144

4,1.641332,1.641166,1.637950,1.640760

5,1.636041,1.637437,1.640702,1.633678

My goal is to convert this data into JSON format. I used an online converter and received the following results:

[

 {

   "1": 2,

   "1.635946": 1.642825,

   "1.636609": 1.640267,

   "1.640240": 1.639013,

   "1.636091": 1.636568

 },

 {

   "1": 3,

   "1.635946": 1.636835,

   "1.636609": 1.636022,

   "1.640240": 1.637664,

   "1.636091": 1.637144

 }

]

I would like guidance on which parts of my existing code need modifications to achieve this conversion.

Here's a snippet of my current code:

var Timer;
var i = 0 ;
    setTimeout(function(){
        Timer = setInterval(function(){

            port.write(meascommand+'\n');
            i++;

            if(i==5){
                clearInterval(Timer);
            }
        },5000);
    },1000);

port.on('data',function(devicevalue){
    arrayvalue = devicevalue.toString();
    eachvalue = arrayvalue.split(';');
var results = [];

            var index = i ; 
            var ch0value = eachvalue[0] ; 
            var ch1value = eachvalue[1] ; 
            var ch2value = eachvalue[2] ; 
            var ch3value = eachvalue[3] ; 

            results[0] = index ;
            results[1] = ch0value ;
            results[2] = ch1value ;
            results[3] = ch2value ;
            results[4] = ch3value ;

            console.log(results);

            fs.appendFile(file,results+'\r\n',function(err){
                if(err)
                    console.log(err);
            });
        });

};

Answer №1

function handleFiles(files) {
    var selectedFile = files[0];
    var fileReader = new FileReader();
    fileReader.onload = function (event) {
        var outputElement = document.getElementById("fileOutput");
        var textData = event.target.result;
        convertCSVtoJSON(textData);
    };
    fileReader.readAsText(selectedFile);
}
function convertCSVtoJSON(csvData) {
    var linesArray = csvData.split("\n");
    var finalResult = [];
    var columnHeaders;
    for (var i = 0; i < linesArray.length; i++) {
        columnHeaders = linesArray[i].split("\n");
    }
    var counter = 0;
    for (var i = 0; i < linesArray.length; i++) {

        var jsonObject = {};
        var currentLine = linesArray[i].split("\n");
        for (var j = 0; j < columnHeaders.length; j++) {
            jsonObject[counter] = currentLine[j];
        }
        counter++;
        finalResult.push(jsonObject);
    }

    return JSON.stringify(finalResult); //JSON
}

Answer №2

Take a look at the code snippet below. Full credit goes to: https://gist.github.com/iwek/7154578

PLEASE NOTE: The use of split(","). If lines contain a ,, this snippet may not work as intended. However, based on your data, it seems like this won't be an issue.

function csvJSON(csv){
  var lines=csv.split("\n");

  var result = [];

  var headers=lines[0].split(",");

  for(var i=1;i<lines.length;i++){

      var obj = {};
      var currentline=lines[i].split(",");

      for(var j=0;j<headers.length;j++){
          obj[headers[j]] = currentline[j];
      }

      result.push(obj);

  }

  //return result; //JavaScript object
  return JSON.stringify(result); //JSON
}

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

Obtain information from a file containing nested JSON objects in R

I am new to utilizing R for programming and I am currently attempting to parse a file that contains nested JSON objects and convert it into an R dataframe. The file format is structured as follows: { "collect": [{ ... // Data details ...

Vue JSON Response Guide

Inquiry from a beginner. My goal is to display the name of a city using props. When I use {{ props.feed.location }} to fetch: { "latitude": 50.85, "longitude": 4.35, "name": "Brussels, Belgium", "id": 213633143 } However, when I attempt {{ props.feed.l ...

What could be causing this conflicting behavior with the logical "and" operator?

const {DEMO, PORT, LOCAL} = process.env; const socketAddress = (DEMO & LOCAL)? `http://${hostname}:${PORT}`: `wss://${hostname}`; When DEMO is false, PORT is undefined, and LOCAL is true The hostname being used is http://9f9cbf19.ngrok.io I verified ...

PHP is unable to provide a JSON response

What could be causing a PHP file not to respond as JSON, while it responds correctly to the connected file? File Response Code <?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); include '.. ...

Unconventional login processes showcased in Redux-Saga's documentation

When looking at the login flow example in the redux-saga documentation, it is clear that the expected action sequence is well-defined. However, does the LOGOUT action always follow the LOGIN action? In real-world scenarios, such as when a user's sessi ...

Sending numerous parameters in ajax call to the C# backend function

I'm encountering an issue with passing multiple parameters from my ajax function to my C# function. When I only pass one parameter (vthaForm) in the ajax function, it is properly sent to the OnPostApprove method with all properties filled out. However ...

adjusting the font color based on the currently selected tab

After seeking help for my previous question on Unable to add a background colour to the button in navigation I have successfully resolved that issue and continued working, but now I am facing a new challenge. I need to change the font color of the navigat ...

What are the steps to modifying the material characteristics of a model loaded using OBJ + MTLLoader?

After successfully loading an .obj model along with its corresponding .mtl file to correctly map the materials onto the model, I noticed that the loaded model appears very dark. To brighten it up, I attempted to change the emissive color to white but encou ...

How can you utilize the Array submission syntax within HTML coding?

I currently have numerous input fields within a form, and some of them are structured like this: <input name="agents[]" type="file" /> Additionally, imagine there is a plus button next to this field as shown below: <img src="plus.jpg" id="some_ ...

Updating Bootstrap modal content based on button clickExplanation on how to dynamically change the content

I am looking to dynamically change the content displayed inside a modal based on the button that is clicked. For example, clicking button one will only show the div with the class 'one' while hiding the others. $('#exampleModalCenter&a ...

Click on the following link to view your screen resolution:

As I work on a website that showcases an animation with a resolution of 1024x768, I plan to distribute the link as a Holiday greeting through email. Is there a method to ensure that the website only loads in the specified resolution, even if the user' ...

Comparing Mongoose and MongoDB in Node.js: Weighing the Benefits of Each

Just starting out with Node.js and noticing the multitude of libraries available to work with MongoDB. The two most popular options appear to be mongoose and mongodb. Can someone provide a comparison of the pros and cons of these extensions? Are there any ...

Can you guide me on how to export a named function using module.exports?

I have a script file for my discord bot that includes a specific command and a function with parsing logic that I want to reuse in my main index.js // File: ./commands/scrumPrompt.js // The function const extractDeets = function (f, scrum) { let items ...

Using reduce() to group items in an array based on a specific object property

Creating a new array grouped by the property 'desc' of the objects within an existing array is my current task. Here is how I envision it: const sourceArray = [ { id: 'id1', sourceDesc: 'foo', prop1: 'ignoreme', p ...

Error in bundle.js at line 25872: A critical error has occurred due to excessive re-renders. React has imposed a limit on the number of renders to avoid an infinite loop. Learn how to resolve

I am currently working on CRUD operations to update data. How can I avoid this error: "Too many re-renders. React limits the number of renders to prevent an infinite loop?" import React,{useEffect,useState} from 'react'; import { NavLink } from ...

Using Vue to alter data through mutations

Greetings! I am currently in the process of developing a website for storing recipes, but as this is my first project, I am facing a challenge with modifying user input data. My goal is to create a system where each new recipe added by a user generates a u ...

What is the best way to showcase a collection of items using a table layout in JavaScript?

I am relatively new to React/JS programming and I'm struggling to understand why my code isn't working correctly. My goal is to create a column with rows based on the items in my Array, but only the header of the table is displaying. After looki ...

Express.js post method malfunctioning for BMI calculation

Currently, I am working on a BMI calculator application in JavaScript as part of my practice. The app is supposed to take two inputs - weight and height, calculate the BMI, and display the result on the web page. However, after inputting the data and submi ...

Troubleshooting problems with saving server data to core data in a background thread

Dealing with concurrency can be quite a headache. I've read numerous articles on how to parse and save server data to Core Data, but many tutorials out there are quite basic and don't address the issue of threading. However, when developing an ap ...

Tips for adding a class to the end of the DOM class

Greetings! I'm currently working with the code below: for ( let x: number = 0; x < this._vcr.element.nativeElement.querySelectorAll(".ui-steps-item").length; x++) { let className: any = this._vcr.element.nativeElement.querySelectorAll( ...