Convert CSV data to JSON with gobble.
First, you need to have gobble installed - see the gobble readme for details. Then,
npm i -D gobble-csvtojson
gobblefile.js
var gobble = require( 'gobble' );
module.exports = gobble( 'src/data' ).map( 'csvtojson', {
parseValues: false, // default `true`
includeNullValues: true, // default `false`
space: ' ' // default `undefined`
});
The second argument is optional:
- parseValues - if
true
, values will be parsed withJSON.parse()
- e.g. numbers will be stored as numbers,true
andfalse
will be stored as booleans, and so on. Otherwise, all values will be stored as strings - includeNullValues - if
true
,null
or missing values will not be added to objects - space - passed to
JSON.stringify()
, useful if readability is more important than the filesize of the resulting JSON
This isn't using a robust, battle-tested CSV parser - it's using a few brittle hacks (I needed something quickly and didn't have time to evaluate all the options). Contributions welcome!
Your CSV is expected to be well-formed, and to have a header row (headers become the keys of each JSON object).
It goes something like this - CSV goes in...
id,first_name,last_name,email
1,Judith,Hunt,[email protected]
2,Phyllis,Crawford,[email protected]
3,Randy,Davis,
4,Christina,Fowler,[email protected]
5,Judith,Wagner,[email protected]
...JSON comes out. Note that the IDs are numeric, and Randy doesn't have an email
property, because we're using the default options here:
[{"id":1,"first_name":"Judith","last_name":"Hunt","email":"[email protected]"},
{"id":2,"first_name":"Phyllis","last_name":"Crawford","email":"[email protected]"},
{"id":3,"first_name":"Randy","last_name":"Davis"},
{"id":4,"first_name":"Christina","last_name":"Fowler","email":"[email protected]"},
{"id":5,"first_name":"Judith","last_name":"Wagner","email":"[email protected]"}]
(Mock data via mockaroo.com.)
MIT. Copyright 2014 Rich Harris