Created
May 27, 2021 13:14
-
-
Save SpenceDiNicolantonio/24d78728b60abda7107a1a5eb51564ef to your computer and use it in GitHub Desktop.
[TSV to JSON] Convert a tab-separated-values file's contents to a set of JSON objects #json #tsv #lodash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'lodash'; | |
/** | |
* Converts a tab-separted-values (TSV) file to a set of JSON objects | |
* where each value is keyed according to the heading row | |
*/ | |
const tsvToJson = tsv => { | |
// Split lines and filter any empties | |
const lines = tsv | |
.split('\n') // Split lines | |
.map(line => line.trim()) // Trim excess whitespace | |
.filter(line => line.trim()); // Filter empty lines | |
// Split each line by tab char | |
const data = lines.map(line => line.split('\t').map(value => value.trim())); | |
// Separate heading (property names) from data | |
const props = data[0]; // Store heading | |
data.shift(); // Remove heading from dataset | |
// Convert each data entry to an object | |
return data.map(entry => _.zipObject(props, entry)); | |
}; | |
export default tsvToJson; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment