Skip to content

Instantly share code, notes, and snippets.

@saily
Last active November 21, 2018 10:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saily/f8a9f72c6b064d51f09040d66e981240 to your computer and use it in GitHub Desktop.
Save saily/f8a9f72c6b064d51f09040d66e981240 to your computer and use it in GitHub Desktop.
Restore JSON hierarchy in Weblate PRE_COMMIT_SCRIPTS
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import argparse
import codecs
import json
__author__ = 'Daniel Widerin <daniel@widerin.net>'
__license__ = 'MIT'
class HierarchicalDict(dict):
def __init__(self, *args, **kwargs):
self.update(*args, **kwargs)
def __setitem__(self, key, val):
dict.__setitem__(self, key, val)
def update(self, *args, **kwargs):
for key, val in dict(*args, **kwargs).items():
keys = key.split('.')
if len(keys) > 1:
self._decode(keys, val)
else:
self[key] = val
def _decode(self, keys, value):
storage = self
for key0 in keys[:-1]:
if key not in storage:
storage[key] = {}
storage = storage[key]
storage[keys[-1]] = value
def main():
parser = argparse.ArgumentParser(
description='Recover flattened json file.')
parser.add_argument(
'files', metavar='FILE', type=str, nargs='+',
help='Files to process')
parser.add_argument(
'--indent', default=4, type=int, dest='indent',
help='json indentation for outfile')
args = parser.parse_args()
for filename in args.files:
try:
raw = codecs.open(filename, 'r', encoding='utf-8').read()
data = json.loads(raw, object_pairs_hook=HierarchicalDict)
with codecs.open(filename, 'w', encoding='utf-8') as outfile:
json.dump(data, outfile,
sort_keys=True,
indent=args.indent,
ensure_ascii=False)
except Exception as ex:
print('Error processing {0:s}'.format(filename), ex)
if __name__ == '__main__':
main()
@saily
Copy link
Author

saily commented May 6, 2016

I wrote a blog post how to use this: http://widerin.net/blog/weblate-i18next-json-parser/

@rolinh
Copy link

rolinh commented Oct 21, 2016

Thanks for this script!

What about changing this line:

#!/usr/bin/env python2.7

into

#!/usr/bin/env python

And using 2to3 to make it possible to run it on either version of python?

@saily
Copy link
Author

saily commented Jan 23, 2017

@rolinh should work fine on python3

@cescp
Copy link

cescp commented Jun 21, 2017

Thanks for the script!
But line 30 should be:
for key in keys[:-1]:

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