Skip to content

Instantly share code, notes, and snippets.

@LegitDongo
Created February 27, 2018 04:01
Show Gist options
  • Save LegitDongo/7d024aac94c9e3de0c6c82a77ac007fc to your computer and use it in GitHub Desktop.
Save LegitDongo/7d024aac94c9e3de0c6c82a77ac007fc to your computer and use it in GitHub Desktop.
Organize PA json
import json
import os
from glob import glob
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
class SortedListEncoder(json.JSONEncoder):
def encode(self, obj):
def sort_lists(item):
if isinstance(item, list):
return sorted(sort_lists(i) for i in item)
elif isinstance(item, dict):
return {k: sort_lists(v) for k, v in item.items()}
else:
return item
return super(SortedListEncoder, self).encode(sort_lists(obj))
def get_path(path):
if not os.path.isabs(path): # If not absolute path
path = os.path.join(ROOT_PATH, path)
return path
def repeat(repeat_this, times):
r = ''
ran_this = 0
while ran_this < times:
r += repeat_this
ran_this += 1
return r
def check(check_key, check_item):
my_key = check_key
my_item = {}
if isinstance(check_item, dict):
for new_key, i in check_item.items():
my_item.update(check(new_key, i))
else:
my_item = check_item
try:
is_int = int(check_key)
except ValueError:
is_int = None
if is_int is not None:
my_key = str(repeat('0', 3 - len(check_key))) + check_key
return {my_key: my_item}
if __name__ == '__main__':
files = glob(get_path('locales/*.json'))
for file_ in files:
to_write = ''
with open(file_, 'rb+') as f:
j = json.loads(f.read())
my_items = {}
for key, value in j.items():
my_items.update(check(key, value))
to_write = json.dumps(my_items, indent=2, sort_keys=True,
cls=SortedListEncoder)
f.close()
with open(file_, 'wb+') as f:
f.write(to_write)
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment