Skip to content

Instantly share code, notes, and snippets.

@troykinsella
Created November 4, 2016 01:07
Show Gist options
  • Save troykinsella/72796eaceebbb0bf4ea9bef7d8c33368 to your computer and use it in GitHub Desktop.
Save troykinsella/72796eaceebbb0bf4ea9bef7d8c33368 to your computer and use it in GitHub Desktop.
Convert json into a flat text format
#!/usr/bin/env node
var fs = require('fs');
var str = fs.readFileSync("/dev/stdin", "utf8");
var json = JSON.parse(str);
function print(path, o) {
if (Array.isArray(o)) {
printArray(path, o);
} else if (typeof o === 'object') {
printObject(path, o);
} else {
printValue(path, o);
}
}
function printValue(path, val) {
if (typeof val === 'string') {
val = '"' + val + '"';
}
console.log(path.substring(1) + ": " + val);
}
function printArray(path, arr) {
arr.forEach(function(v, i) {
print(path + "[" + i + "]", v);
});
}
function printObject(path, o) {
Object.keys(o).forEach(function(key) {
var val = o[key];
print(path + '.' + key, val);
});
}
print('', json);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment