Skip to content

Instantly share code, notes, and snippets.

@Hasimir
Last active April 22, 2018 09:42
Show Gist options
  • Save Hasimir/deee35beb83e19a84e238aa346444049 to your computer and use it in GitHub Desktop.
Save Hasimir/deee35beb83e19a84e238aa346444049 to your computer and use it in GitHub Desktop.
Quick and dirty method of making walls of text JSON files indented properly (note, not standards and tab width compliant, just easier to read).
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals
# Copyright (C) 2018 Ben McGinnes <[email protected]>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License and the GNU
# Lesser General Public Licensefor more details.
#
# You should have received a copy of the GNU General Public License and the GNU
# Lesser General Public along with this program; if not, see
# <http://www.gnu.org/licenses/>.
import json
import pprint
import shutil
import sys
"""
Description: will read the JSON file and rewrite it with
indentationand decent formatting (but no word wrap). The
original file will be moved to <filename>.bak.
"""
print("""
Usage: jsondentation.py <filename>
""")
if len(sys.argv) < 2:
print("You must enter a filename.")
elif len(sys.argv) >= 2:
files = sys.argv[1:]
for i in range(len(files)):
filename = files[i]
bakfile = "{0}.bak".format(filename)
with open(filename, "rb") as f:
fn0 = f.read()
fn1 = json.loads(fn0)
fn2 = pprint.pformat(fn1)
shutil.move(filename, bakfile)
with open(filename, "w") as f:
f.write(fn2)
else:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment