Created
December 15, 2022 18:18
-
-
Save BoDonkey/bcba9141e21faac535a442469c470eb1 to your computer and use it in GitHub Desktop.
Translates an i18n JSON file to a different language
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs').promises; | |
const translate = require('google-translate-api-x'); | |
async function translateIt(file) { | |
try { | |
// read file and parse it as JSON | |
const data = await fs.readFile(file, 'utf8'); | |
const obj = JSON.parse(data); | |
// prepare an array of translation keys and an array of translation strings | |
const translationKeys = Object.keys(obj); | |
const translationStrings = Object.values(obj); | |
// translate the strings and store the result in an array | |
const translations = await translate(translationStrings, { from: 'en', to: 'de' }); | |
// create a new object with the translation keys and the translated strings | |
const translatedJson = translationKeys.reduce((acc, key, i) => { | |
acc[key] = translations[i].text; | |
return acc; | |
}, {}); | |
// write the translated JSON to a file | |
const jsonString = JSON.stringify(translatedJson); | |
await fs.writeFile('de.json', jsonString); | |
} catch (err) { | |
console.error('Failed to translate file', err); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment