Skip to content

Instantly share code, notes, and snippets.

@BoDonkey
Created December 15, 2022 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BoDonkey/bcba9141e21faac535a442469c470eb1 to your computer and use it in GitHub Desktop.
Save BoDonkey/bcba9141e21faac535a442469c470eb1 to your computer and use it in GitHub Desktop.
Translates an i18n JSON file to a different language
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