0

Hello friends I have found this problem and for more than I wanted to solve it I could not, I need to take the data from a .csv file and export it to a json, but this must be grouped in a recursive way an example would be the following:

Example data

The result:

labels: [
    {
      label: 'Camion',
      children: [
        {
          label: '6002577',
        },
        '6008971',
        '6008979'
      ]
    },
    {
      label: 'Delivery',
      children: ['6001265', '6001273', '6001458', '6001466', '6001587', '6001595', '6002570', '6002578', '6008972', '6008980']
    },
    {
      label: 'Moto',
      children: ['6001263', '6001271', '6001459', '6001467', '6001588', '6001596', '6002568', '6002576', '6008973', '6008981']
    }
  ]

The .csv data is dynamic and can have n columns and n records

  • 5
    What have you tried so far? Where are you stuck? – Mark Dec 10 '18 at 15:34
  • 3
    Welcome to SO. You might find reading the site [help section](https://stackoverflow.com/help) useful when it comes to [asking a good question](https://stackoverflow.com/help/how-to-ask). To get the best answers to your question we like to see a) that you've attempted to solve the problem yourself first, and b) used a [mcve] to narrow down the problem. Asking SO to do all the work for you doesn't help you or us. [Here's a question checklist you might find useful.](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist). – Andy Dec 10 '18 at 15:41
  • In the management of recursion is not placing children with parents. – Luis Berna Dec 10 '18 at 15:45

1 Answers1

0

This or this should do the trick. Example from the above StackOverflow answer:

//var csv is the CSV file with headers
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
}

Use like this: var json = csvToJSON(csv);

TheFlyBiker 420
  • 69
  • 1
  • 13