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!

2
  • 3
    Pretty sure the last key in the myObj should be Tree, not Cat again, right? Commented Dec 19, 2018 at 22:23
  • Yes you're right, great spot @CertainPerformance! Commented Dec 20, 2018 at 8:32

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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);

Comments

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.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.