-
Notifications
You must be signed in to change notification settings - Fork 2
/
json-to-android-xml.py
61 lines (53 loc) · 1.96 KB
/
json-to-android-xml.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import argparse
import json
import cgi
import csv
import sys
import re
assert sys.version_info >= (3, 6), "Python >= 3.6 is required"
# Special replacement class that counts the matches
class ReplaceCounter(object):
def __init__(self):
self.idx = 0
def __call__(self, match):
self.idx += 1
return "%{}$s".format(self.idx)
def dict_to_android_xml(d, out_path):
with open(out_path, 'w') as out_file:
out_file.write('<?xml version="1.0" encoding="utf-8"?>\n')
out_file.write('<resources>\n')
for key, text in d.items():
key = key.replace('.', '_')
# We need to increase a counter for every match
text = re.sub(
r'\{(\w+)\}',
ReplaceCounter(),
text,
)
text = text.replace("&", "&")
text = text.replace('"', '\"')
text = text.replace("'", "\'")
text = text.replace("'", "\'")
text = text.replace("\n", "\\n")
# This regexp will match any unescaped ' and " also when it appears at
# the beginning of the string.
text = re.sub(r'([^\\])\'|^\'', '\g<1>\\\'', text)
text = re.sub(r'([^\\])\"|^\"', '\g<1>\\\"', text)
out_file.write(' <string name="{}">{}</string>'.format(key, text))
out_file.write('\n')
out_file.write('</resources>\n')
def load_json(in_path):
with open(in_path) as in_file:
return json.load(in_file)
def parse_args():
p = argparse.ArgumentParser(description='translations: CSV to KEYVALUEJSON')
p.add_argument('--json', metavar='PATH', help='json input path', required=True)
p.add_argument('--xml', metavar='PATH', help='android XML output path', required=True)
opt = p.parse_args()
return opt
def main():
opt = parse_args()
dict_to_android_xml(load_json(opt.json), opt.xml)
print("{} written".format(opt.xml))
if __name__ == "__main__":
main()