Created
July 6, 2015 20:25
-
-
Save nichochar/e88d63d8032478116ce0 to your computer and use it in GitHub Desktop.
json file indenter script
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 python | |
| # Takes in a file as an input, and creates a file with the same name | |
| # with the suffix ".clean" | |
| __author__ = 'Nicholas Charriere' | |
| __VERSION__ = 0.1 | |
| import argparse | |
| import sys | |
| import json | |
| def create_parser(): | |
| parser = argparse.ArgumentParser(description='JSON indenter script') | |
| parser.add_argument( | |
| '-f', | |
| '--filename', | |
| type=str, | |
| help='the path to the json to be indented properly') | |
| parser.add_argument( | |
| '-o', | |
| '--output-filename', | |
| type=str, | |
| help='optional output filename parameter') | |
| parser.add_argument( | |
| '-i', | |
| '--indent', | |
| type=int, | |
| default=4) | |
| return parser | |
| def parse_args(parser): | |
| '''Parses the arguments from the parser passed in as argument. | |
| Validates them, raises errors if they don't match | |
| Returns | |
| ------- | |
| input_filename: str | |
| the filename used for input | |
| output_filename: str | |
| the filename used for output | |
| indent: int | |
| the number of indent spaces for indenting the file. Defaults to 4 | |
| ''' | |
| args = parser.parse_args() | |
| if not args.filename: | |
| sys.exit('You need the --filename (-f) parameter') | |
| if args.output_filename: | |
| output_filename = args.output_filename | |
| else: | |
| output_filename = args.filename + '.clean' | |
| return args.filename, output_filename, args.indent | |
| def main(): | |
| '''Creates argument parser and runs script | |
| ''' | |
| parser = create_parser() | |
| input_filename, output_filename, indent = parse_args(parser) | |
| with open(input_filename, 'r') as input_file: | |
| dirty_json = json.load(input_file) | |
| with open(output_filename, 'w') as output_file: | |
| json.dump(dirty_json, output_file, indent=indent) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment