Skip to content

Instantly share code, notes, and snippets.

@peter88213
Created December 31, 2024 10:58
Show Gist options
  • Save peter88213/7d0ca8f05fb1fa95eb02b39d356f0385 to your computer and use it in GitHub Desktop.
Save peter88213/7d0ca8f05fb1fa95eb02b39d356f0385 to your computer and use it in GitHub Desktop.
Convert a .ts XML translation file to JSON
"""Convert a .ts XML translation file.
Output:
- a JSON file (extension ".json")
Usage:
ts_json.py sourcefile
Copyright (c) 2024 Peter Triesberger
For further information see https://github.com/peter88213/
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
import os
import sys
import xml.etree.ElementTree as ET
import json
def read_ts_file(tsFile):
xmlRoot = ET.parse(tsFile).getroot()
translations = {}
for xmlContext in xmlRoot.iterfind('context'):
context = xmlContext.find('name').text
translations[context] = {}
for xmlMessage in xmlContext.iterfind('message'):
translations[context][xmlMessage.find('source').text] = xmlMessage.find('translation').text
return translations
def write_json_file(translations, jsonFile):
with open(jsonFile, 'w', encoding='utf-8') as f:
json.dump(translations, f, ensure_ascii=False, sort_keys=True, indent=2)
def main(tsFile):
translations = read_ts_file(tsFile)
root, __ = os.path.splitext(tsFile)
write_json_file(translations, f'{root}.json')
if __name__ == '__main__':
main(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment