Created
April 13, 2022 04:34
-
-
Save nhridoy/f11e36587ed35090473136ce5c6a69fe to your computer and use it in GitHub Desktop.
Python Script to minify JSON files
This file contains 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
import os | |
import json | |
def minify(filename): | |
newname = filename.replace('.json', '.min.json') # Output file name | |
new_file_location = os.path.join( | |
'./compressed/', newname) # Output file location | |
with open(filename, encoding="utf8") as fp: | |
print("Compressing file: " + filename) | |
print('Compressing...') | |
jload = json.load(fp) | |
newfile = json.dumps(jload, indent=None, separators=( | |
',', ':'), ensure_ascii=False) | |
# newfile = str.encode(newfile) # remove this | |
with open(new_file_location, 'w', encoding="utf8") as f: # add encoding="utf8" | |
f.write(newfile) | |
print('Done!') | |
print('Compressed file name:', newname) | |
print('Original file size:', len( | |
open(filename, 'r', encoding="utf8").read())) | |
print('Compressed file size:', len( | |
open(new_file_location, 'r', encoding="utf8").read())) | |
print('Compression ratio:', len(open(new_file_location, 'r', encoding="utf8").read() | |
)/len(open(filename, 'r', encoding="utf8").read())) | |
def main(): | |
cwd = os.getcwd() # Get the current working directory (cwd) | |
files = os.listdir(cwd) # Get all the files in that directory | |
dirName = 'compressed' | |
if not os.path.exists(dirName): | |
os.mkdir(dirName) | |
print("Directory ", dirName, " Created ") # Output directory created | |
print("Files in %r: %s" % (cwd, files)) | |
for f in files: | |
if f.endswith('.json'): | |
minify(f) | |
print('Compression complete.') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment