0

Unsure on this one - any help hugely appreciated!

Using ideally just an online converter, or if not perhaps a node package, I'm trying to convert a CSV file like this:

Cat,31.2,31.2
Dog,35,1
Tree,32.4

into this:

"myObj":{
   "Cat":[
      31.2,
      31.2
   ],
   "Dog":[
      35,
      1
   ],
   "Tree":[
      32.4
   ]
}

What I've tried

Have tried sites like this and this, but couldn't see how I could adapt them for my needs.

Thanks so much for any ideas on how to do this!

hardanger
  • 2,349
  • 1
  • 16
  • 23

4 Answers4

2
const fs = require('fs');
const csv = fs.readFileSync(process.argv[2], 'utf8');
const obj = csv.split(/\r?\n/g)
  .filter(line => line.trim())
  .map(line => line.split(','))
  .reduce(
    (o, [key, ...values]) => Object.assign(o, { [key]: values.map(Number) }),
    {}
  );

fs.writeFileSync(process.argv[3], JSON.stringify(obj, null, 3), 'utf8');

After saving this to csv2json.js or something like that, you can use it on the Command Line like this:

node csv2json input.csv output.json
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
  • Thanks a ton for all the responses! Chose this as correct as it was the most complete - though in case anyone needs something similar - for my needs I had to change empty cells from 0 to empty, convert values to numbers and remove empty rows. – hardanger Dec 20 '18 at 18:59
1

For the sort of input posted, it's quite easy to transform it into an object manually, by splitting by newlines and reduceing into an object:

const input = `Cat,31.2,31.2
Dog,35,1
Tree,32.4`;
const obj = input.split('\n').reduce((a, line) => {
  const [, heading, rest] = line.match(/^([^,]+),(.*)/);
  a[heading] = rest.split(',');
  return a;
}, {});
console.log(obj);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

You could write a function that does what you want, it's not that hard:

function csv2json (csv) {
  let arr = csv.split('\n'), // Split your CSV into an array of lines
      obj = {}               // Your object to later fill data into

  for (let i = 0; i < arr.length; i++) {
    let line = arr[i].split(',')    // Split the line into an array

    obj[line.shift()] = line        // Remove the first item from the array 
                                    // and use it as the key in the object,
                                    // assigning the rest of the array to
                                    // that key
  }

  return obj   // Return your object
}

You can later write the JSON to a file using fs.writeFile(...) or process it further in your application.

Benni
  • 778
  • 8
  • 22
0

const str = `Cat,31.2,31.2
Dog,35,1
Tree,32.4`;

const obj = str.split('\n').reduce((accu, curr) => {
    curr = curr.split(',');
    let first = curr.shift();
    accu[first] = [...curr];
    return accu;
}, {});

console.log(obj);
random
  • 7,756
  • 3
  • 19
  • 25