Created
November 4, 2016 01:07
-
-
Save troykinsella/72796eaceebbb0bf4ea9bef7d8c33368 to your computer and use it in GitHub Desktop.
Convert json into a flat text format
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
#!/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