| 1 |
#!/usr/bin/env python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
""" |
| 4 |
Utility script to format/beautify one or more JSON files. |
| 5 |
|
| 6 |
REQUIRES: Python >= 2.6 (json module is part of Python standard library) |
| 7 |
LICENSE: BSD |
| 8 |
""" |
| 9 |
|
| 10 |
from __future__ import absolute_import |
| 11 |
|
| 12 |
__author__ = "Jens Engel" |
| 13 |
__copyright__ = "(c) 2011-2013 by Jens Engel" |
| 14 |
VERSION = "0.2.2" |
| 15 |
|
| 16 |
# -- IMPORTS: |
| 17 |
import os.path |
| 18 |
import glob |
| 19 |
import logging |
| 20 |
from optparse import OptionParser |
| 21 |
import sys |
| 22 |
try: |
| 23 |
import json |
| 24 |
except ImportError: |
| 25 |
import simplejson as json #< BACKWARD-COMPATIBLE: Python <= 2.5 |
| 26 |
|
| 27 |
|
| 28 |
# ---------------------------------------------------------------------------- |
| 29 |
# CONSTANTS: |
| 30 |
# ---------------------------------------------------------------------------- |
| 31 |
DEFAULT_INDENT_SIZE = 2 |
| 32 |
|
| 33 |
# ---------------------------------------------------------------------------- |
| 34 |
# FUNCTIONS: |
| 35 |
# ---------------------------------------------------------------------------- |
| 36 |
def json_format(filename, indent=DEFAULT_INDENT_SIZE, **kwargs): |
| 37 |
""" |
| 38 |
Format/Beautify a JSON file. |
| 39 |
|
| 40 |
:param filename: Filename of a JSON file to process. |
| 41 |
:param indent: Number of chars to indent per level (default: 4). |
| 42 |
:returns: >= 0, if successful (written=1, skipped=2). Zero(0), otherwise. |
| 43 |
:raises: ValueError, if parsing JSON file contents fails. |
| 44 |
:raises: json.JSONDecodeError, if parsing JSON file contents fails. |
| 45 |
:raises: IOError (Error 2), if file not found. |
| 46 |
""" |
| 47 |
console = kwargs.get("console", logging.getLogger("console")) |
| 48 |
encoding = kwargs.get("encoding", None) |
| 49 |
dry_run = kwargs.get("dry_run", False) |
| 50 |
if indent is None: |
| 51 |
sort_keys = False |
| 52 |
else: |
| 53 |
sort_keys = True |
| 54 |
|
| 55 |
message = "%s ..." % filename |
| 56 |
# if not (os.path.exists(filename) and os.path.isfile(filename)): |
| 57 |
# console.error("%s ERROR: file not found.", message) |
| 58 |
# return 0 |
| 59 |
|
| 60 |
contents = open(filename, "r").read() |
| 61 |
data = json.loads(contents, encoding=encoding) |
| 62 |
contents2 = json.dumps(data, indent=indent, sort_keys=sort_keys) |
| 63 |
contents2 = contents2.strip() |
| 64 |
contents2 = "%s\n" % contents2 |
| 65 |
if contents == contents2: |
| 66 |
console.info("%s SKIP (already pretty)", message) |
| 67 |
return 2 #< SKIPPED. |
| 68 |
elif not dry_run: |
| 69 |
outfile = open(filename, "w") |
| 70 |
outfile.write(contents2) |
| 71 |
outfile.close() |
| 72 |
console.warn("%s OK", message) |
| 73 |
return 1 #< OK |
| 74 |
|
| 75 |
def json_formatall(filenames, indent=DEFAULT_INDENT_SIZE, dry_run=False): |
| 76 |
""" |
| 77 |
Format/Beautify a JSON file. |
| 78 |
|
| 79 |
:param filenames: Format one or more JSON files. |
| 80 |
:param indent: Number of chars to indent per level (default: 4). |
| 81 |
:returns: 0, if successful. Otherwise, number of errors. |
| 82 |
""" |
| 83 |
errors = 0 |
| 84 |
console = logging.getLogger("console") |
| 85 |
for filename in filenames: |
| 86 |
try: |
| 87 |
result = json_format(filename, indent=indent, console=console, |
| 88 |
dry_run=dry_run) |
| 89 |
if not result: |
| 90 |
errors += 1 |
| 91 |
# except json.decoder.JSONDecodeError, e: |
| 92 |
# console.error("ERROR: %s (filename: %s)", e, filename) |
| 93 |
# errors += 1 |
| 94 |
except Exception as e: |
| 95 |
console.error("ERROR %s: %s (filename: %s)", |
| 96 |
e.__class__.__name__, e, filename) |
| 97 |
errors += 1 |
| 98 |
return errors |
| 99 |
|
| 100 |
# ---------------------------------------------------------------------------- |
| 101 |
# MAIN FUNCTION: |
| 102 |
# ---------------------------------------------------------------------------- |
| 103 |
def main(args=None): |
| 104 |
"""Boilerplate for this script.""" |
| 105 |
if args is None: |
| 106 |
args = sys.argv[1:] |
| 107 |
|
| 108 |
usage_ = """%prog [OPTIONS] JsonFile [MoreJsonFiles...] |
| 109 |
Format/Beautify one or more JSON file(s).""" |
| 110 |
parser = OptionParser(usage=usage_, version=VERSION) |
| 111 |
parser.add_option("-i", "--indent", dest="indent_size", |
| 112 |
default=DEFAULT_INDENT_SIZE, type="int", |
| 113 |
help="Indent size to use (default: %default).") |
| 114 |
parser.add_option("-c", "--compact", dest="compact", |
| 115 |
action="store_true", default=False, |
| 116 |
help="Use compact format (default: %default).") |
| 117 |
parser.add_option("-n", "--dry-run", dest="dry_run", |
| 118 |
action="store_true", default=False, |
| 119 |
help="Check only if JSON is well-formed (default: %default).") |
| 120 |
options, filenames = parser.parse_args(args) #< pylint: disable=W0612 |
| 121 |
if not filenames: |
| 122 |
parser.error("OOPS, no filenames provided.") |
| 123 |
if options.compact: |
| 124 |
options.indent_size = None |
| 125 |
|
| 126 |
# -- STEP: Init logging subsystem. |
| 127 |
format_ = "json.format: %(message)s" |
| 128 |
logging.basicConfig(level=logging.WARN, format=format_) |
| 129 |
console = logging.getLogger("console") |
| 130 |
|
| 131 |
# -- DOS-SHELL SUPPORT: Perform filename globbing w/ wildcards. |
| 132 |
skipped = 0 |
| 133 |
filenames2 = [] |
| 134 |
for filename in filenames: |
| 135 |
if "*" in filenames: |
| 136 |
files = glob.glob(filename) |
| 137 |
filenames2.extend(files) |
| 138 |
elif os.path.isdir(filename): |
| 139 |
# -- CONVENIENCE-SHORTCUT: Use DIR as shortcut for JSON files. |
| 140 |
files = glob.glob(os.path.join(filename, "*.json")) |
| 141 |
filenames2.extend(files) |
| 142 |
if not files: |
| 143 |
console.info("SKIP %s, no JSON files found in dir.", filename) |
| 144 |
skipped += 1 |
| 145 |
elif not os.path.exists(filename): |
| 146 |
console.warn("SKIP %s, file not found.", filename) |
| 147 |
skipped += 1 |
| 148 |
continue |
| 149 |
else: |
| 150 |
assert os.path.exists(filename) |
| 151 |
filenames2.append(filename) |
| 152 |
filenames = filenames2 |
| 153 |
|
| 154 |
# -- NORMAL PROCESSING: |
| 155 |
errors = json_formatall(filenames, options.indent_size, |
| 156 |
dry_run=options.dry_run) |
| 157 |
console.error("Processed %d files (%d with errors, skipped=%d).", |
| 158 |
len(filenames), errors, skipped) |
| 159 |
if not filenames: |
| 160 |
errors += 1 |
| 161 |
return errors |
| 162 |
|
| 163 |
# ---------------------------------------------------------------------------- |
| 164 |
# AUTO-MAIN: |
| 165 |
# ---------------------------------------------------------------------------- |
| 166 |
if __name__ == "__main__": |
| 167 |
sys.exit(main()) |