-
-
Save sandfox/0379203c5f5979993feca80c46ac6cfc to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
// Usage cat some-file.json | jpoo path.to.Key | |
// Needed the ability to parse + fetch a key from a string of JSON sent to | |
// stdin and be cross platfrom which ruled out jq, and should work with node 4 - BITE ME! | |
const stdin = process.stdin; | |
getStdin = () => { | |
let ret = ''; | |
return new Promise(resolve => { | |
if (stdin.isTTY) { | |
resolve(ret); | |
return; | |
} | |
stdin.setEncoding('utf8'); | |
stdin.on('readable', () => { | |
let chunk; | |
while ((chunk = stdin.read())) { | |
ret += chunk; | |
} | |
}); | |
stdin.on('end', () => { | |
resolve(ret); | |
}); | |
}); | |
}; | |
getStdin().then( str => { | |
try { | |
const obj = JSON.parse(str) | |
const path = process.argv[2].split('.') | |
const res = path.reduce( (o, segment) =>{ | |
if (segment in o){ | |
return o[segment] | |
} | |
throw new Error(`Cannot find key "${segment}"`) | |
}, obj) | |
console.log(res) | |
} catch ({ message }) { | |
if(message.startsWith('Cannot read property \'split\' of undefined')) { | |
console.error('Error: No path selector supplied') | |
} else if(message === 'Unexpected end of JSON input') { | |
console.error('Error: Invalid json supplied') | |
} else { | |
console.error(message) | |
} | |
process.exit(1) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment