()
| 42 | |
| 43 | |
| 44 | def main(): |
| 45 | description = ('A simple command line interface for json module ' |
| 46 | 'to validate and pretty-print JSON objects.') |
| 47 | parser = argparse.ArgumentParser(description=description, color=True) |
| 48 | parser.add_argument('infile', nargs='?', |
| 49 | help='a JSON file to be validated or pretty-printed; ' |
| 50 | 'defaults to stdin', |
| 51 | default='-') |
| 52 | parser.add_argument('outfile', nargs='?', |
| 53 | help='write the output of infile to outfile', |
| 54 | default=None) |
| 55 | parser.add_argument('--sort-keys', action='store_true', default=False, |
| 56 | help='sort the output of dictionaries alphabetically by key') |
| 57 | parser.add_argument('--no-ensure-ascii', dest='ensure_ascii', action='store_false', |
| 58 | help='disable escaping of non-ASCII characters') |
| 59 | parser.add_argument('--json-lines', action='store_true', default=False, |
| 60 | help='parse input using the JSON Lines format. ' |
| 61 | 'Use with --no-indent or --compact to produce valid JSON Lines output.') |
| 62 | group = parser.add_mutually_exclusive_group() |
| 63 | group.add_argument('--indent', default=4, type=int, |
| 64 | help='separate items with newlines and use this number ' |
| 65 | 'of spaces for indentation') |
| 66 | group.add_argument('--tab', action='store_const', dest='indent', |
| 67 | const='\t', help='separate items with newlines and use ' |
| 68 | 'tabs for indentation') |
| 69 | group.add_argument('--no-indent', action='store_const', dest='indent', |
| 70 | const=None, |
| 71 | help='separate items with spaces rather than newlines') |
| 72 | group.add_argument('--compact', action='store_true', |
| 73 | help='suppress all whitespace separation (most compact)') |
| 74 | options = parser.parse_args() |
| 75 | |
| 76 | dump_args = { |
| 77 | 'sort_keys': options.sort_keys, |
| 78 | 'indent': options.indent, |
| 79 | 'ensure_ascii': options.ensure_ascii, |
| 80 | } |
| 81 | if options.compact: |
| 82 | dump_args['indent'] = None |
| 83 | dump_args['separators'] = ',', ':' |
| 84 | |
| 85 | try: |
| 86 | if options.infile == '-': |
| 87 | infile = sys.stdin |
| 88 | else: |
| 89 | infile = open(options.infile, encoding='utf-8') |
| 90 | try: |
| 91 | if options.json_lines: |
| 92 | objs = (json.loads(line) for line in infile) |
| 93 | else: |
| 94 | objs = (json.load(infile),) |
| 95 | finally: |
| 96 | if infile is not sys.stdin: |
| 97 | infile.close() |
| 98 | |
| 99 | if options.outfile is None: |
| 100 | outfile = sys.stdout |
| 101 | else: |
no test coverage detected
searching dependent graphs…