Skip to content

Instantly share code, notes, and snippets.

@stigok
Created June 11, 2017 23:13
Show Gist options
  • Save stigok/7f6e06bc1f3fd3e8584759f4e144834e to your computer and use it in GitHub Desktop.
Save stigok/7f6e06bc1f3fd3e8584759f4e144834e to your computer and use it in GitHub Desktop.
Return value of property with specified key in JSON object read from stdin
#!/usr/bin/env node
const args = process.argv.slice(2)
const key = args[0]
if (!key) {
console.error('Missing argument')
process.exit(1)
}
let buffer = ''
process.stdin.on('data', (data) => {
if (data) buffer += data.toString()
})
process.stdin.on('end', () => {
const obj = JSON.parse(buffer)
const result = obj[key]
if (typeof result === 'undefined') {
process.exit(2)
}
console.log(result)
})
@stigok
Copy link
Author

stigok commented Jun 11, 2017

  • Expects proper JSON (will fail loudly on invalid syntax)
  • Takes a single argument: key of property's value to return
  • Exits with 0 if named property is undefined
  • Only supports plain objects
  • Only looks on first level for property key

Example

$ echo '{"foo": "bar","hello":"world","fresh":"water","is":"good"}' | jsonprop fresh
water

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment