Skip to content

Instantly share code, notes, and snippets.

@runapp
Created November 23, 2021 11:29
Show Gist options
  • Save runapp/11cb0c24138c95ed47c1888b7ad77695 to your computer and use it in GitHub Desktop.
Save runapp/11cb0c24138c95ed47c1888b7ad77695 to your computer and use it in GitHub Desktop.
Sort json file by key, recursively.
import json
import collections
import os
def sort_keys(x):
if isinstance(x, list):
return [sort_keys(i) for i in x]
elif isinstance(x, dict):
ks = sorted(x.keys())
t = collections.OrderedDict()
for k in ks:
t[k] = sort_keys(x[k])
return t
else:
return x
def f(x):
with open(x, "r", encoding="utf8") as ff:
filedata = ''.join(line for line in ff if not line.lstrip().startswith('//'))
d = json.loads(filedata)
d = sort_keys(d)
with open(x.replace(".json", "2.json"), "w", encoding="utf8") as gg:
json.dump(d, gg, indent=2)
def main():
for i in os.listdir():
if i.endswith("2.json"):
continue
if not i.endswith(".json"):
continue
f(i)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment