Created
November 23, 2021 11:29
-
-
Save runapp/11cb0c24138c95ed47c1888b7ad77695 to your computer and use it in GitHub Desktop.
Sort json file by key, recursively.
This file contains hidden or 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 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