Skip to content

Instantly share code, notes, and snippets.

@bpeterso2000
Last active October 28, 2017 09:05
Show Gist options
  • Save bpeterso2000/c94f374f171037f41eb2df6c81f17016 to your computer and use it in GitHub Desktop.
Save bpeterso2000/c94f374f171037f41eb2df6c81f17016 to your computer and use it in GitHub Desktop.
import json
import sys
import click
import click._termui_impl
class JSONFile(click.File):
name = 'JSON.load'
def __init__(self, **kwds):
super(JSONFile, self).__init__(**kwds)
def convert(self, value, param, ctx):
f = super(JSONFile, self).convert(value, param, ctx)
if click._termui_impl.isatty(sys.stdin):
click.echo(ctx.get_usage())
click.echo("Try `jsonclick --help' for more information.")
return ''
try:
return json.load(f)
except (json.JSONDecodeError, TypeError) as e:
self.fail('%s does not contain valid JSON: %s' % (
click._compat.filename_to_ui(value),
click._compat.get_streerror(e),
), param, ctx)
return ''
@click.command()
@click.argument('jsonfile', default='-', type=JSONFile())
def main(jsonfile):
click.echo(jsonfile)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment