Skip to content

Instantly share code, notes, and snippets.

@KinoAR
Last active March 23, 2023 18:49
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save KinoAR/a5cf8a207529ee643389c4462ebf13cd to your computer and use it in GitHub Desktop.
Save KinoAR/a5cf8a207529ee643389c4462ebf13cd to your computer and use it in GitHub Desktop.
A JSON minify script written in Python.
#!/usr/bin/env python3
"""JSON minify program. """
import json # import json library
import sys # import sys library
def minify(file_name):
"Minify JSON"
file_data = open(file_name, "r", 1).read() # store file info in variable
json_data = json.loads(file_data) # store in json structure
json_string = json.dumps(json_data, separators=(',', ":")) # Compact JSON structure
file_name = str(file_name).replace(".json", "") # remove .json from end of file_name string
new_file_name = "{0}_minify.json".format(file_name)
open(new_file_name, "w+", 1).write(json_string) # open and write json_string to file
ARGS = sys.argv[1:] # get arguments passed to command line excluding first arg
for arg in ARGS: # loop through arguments
minify(arg)
@farhan418
Copy link

Thanks

@shevchenkoartem
Copy link

10x

@HRezaei
Copy link

HRezaei commented Aug 22, 2022

Good job! But in some cases, we prefer not to call json.loads and minify the JSON string without deserializing it to an object. Do you have any suggestion for that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment