Skip to content

Instantly share code, notes, and snippets.

@krrishd
Last active November 8, 2016 21:35
Show Gist options
  • Save krrishd/6827d1d764a4d95e8736 to your computer and use it in GitHub Desktop.
Save krrishd/6827d1d764a4d95e8736 to your computer and use it in GitHub Desktop.

_sv2json

_sv2json is a simple tool to convert files delimited by certain characters/breaks into JSON files.

For example, it allows you to convert CSV or TSV (tab separated values) into JSON.

Usage

First, install _sv2json to your project:

$ npm install sv2json --save

Then, include it in your script/project:

var _sv2json = require('sv2json');

You can then use it as such:

/*
* We assume that the variable 'tsvData' contains data delimited by tabs (\t)
*/

var jsonVersionOfTsvData = _sv2json(tsvData, '\t');
/*
* Converts __ separated value data to JSON
* for example, CSV (comma separated values) or TSV (tab separated values) => JSON
* @param {String} data (should be in CSV/TSV/etc format)
* @param {String} delimiter (TSV: '\t', CSV: ',') (defaults to CSV)
* @returns {Object} json
*
* @author: gist.github.com/krrishd
*/
let _sv2json = (() => {
function convert(data, delimiter) {
let json = [];
let d = data.split('\n');
let keys = d[0].split(delimiter || ',');
d = d.splice(1);
d.forEach(data => {
let keyVal = data.split(delimiter || ',');
let obj = {};
keys.forEach((keyData, n) => {
obj[keyData] = keyVal[n];
});
json.push(obj);
});
return json;
}
return function(data, delimiter) {
return convert(data, delimiter);
}
})();
module.exports = _sv2json;
{
"name": "sv2json",
"version": "0.0.2",
"description": "A tool that allows one to convert files delimited by any particular character or break into JSON (such as CSV or TSV files)",
"main": "_svtojson.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git@gist.github.com:6827d1d764a4d95e8736.git"
},
"keywords": [
"csv",
"tsv",
"json",
"conversion",
"converter"
],
"author": "Krish Dholakiya <krishna.dholakiya@gmail.com>",
"license": "MIT"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment