Skip to content

Instantly share code, notes, and snippets.

@anna-hope
Created January 13, 2015 04:02
Show Gist options
  • Save anna-hope/1c08002524fa15a1f53c to your computer and use it in GitHub Desktop.
Save anna-hope/1c08002524fa15a1f53c to your computer and use it in GitHub Desktop.
restringer for elsa
#!/usr/bin/env python3.4
import json
from pprint import PrettyPrinter
from collections import defaultdict
pp = PrettyPrinter()
with open('elsa/strings.json') as stringfile:
strings = json.load(stringfile)
langs = strings['langs'].keys()
del strings['langs']
class Tree(defaultdict):
def __missing__(self, key):
self[key] = value = self.__class__()
return value
def insert(self, path):
t = self
for node in path:
t = t[node]
def set_nested_value(self, path, value):
# hackety hack
self.insert(path)
t = self
for node in path:
if node == path[-1]:
t[node] = value
break
t = t[node]
def walk(obj, pre=[]):
if obj.keys() == langs:
for lang in langs:
new_strings.set_nested_value([lang] + pre[:], obj[lang])
for k, v in obj.items():
if isinstance(v, dict):
pre.append(k)
walk(v, pre)
try:
del pre[-1]
except IndexError:
pass
new_strings = Tree()
walk(strings)
with open('elsa/new_strings.json', 'w') as new_file:
json.dump(new_strings, new_file, indent=4, ensure_ascii=False, sort_keys=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment