JSON

How to automatically translate JSON files with General Translation

Overview

gtx-cli can be used to automatically translate your project's JSON files, regardless of which i18n library you are using.

Note: We currently support custom string syntax and formatting for the following i18n libraries: next-intl, i18next, gt-next, gt-react.

If you are using a different i18n library, the translation results may not be accurate for strings with custom syntax and formatting (for example, ICU messages). Don’t see your favourite library? Please let us know, and we’ll add it as soon as we can!

We will follow these four steps:

Add your environment variables

Install gtx-cli

Create a gt.config.json file

Tip: Avoid the hassle of using translation files with the <T> component.


Step 1: Add your environment variables

Add your production API key and project ID to your environment variables. This is required to use the gtx-cli tool. You can get these from the General Translation dashboard.

.env
GT_API_KEY=<your API key>
GT_PROJECT_ID=<your project ID>

Step 2: Install gtx-cli

Install the gtx-cli tool in your project.

npm i gtx-cli
yarn add --dev gtx-cli
bun add --dev gtx-cli
pnpm add --save-dev gtx-cli

Step 3: Create a gt.config.json file

Create a gt.config.json file at the root of your project.

gt.config.json
{
  "defaultLocale": "en",
  "locales": ["zh", "es", "ja"],
  "files": {
    "json": {
      "include": ["i18n/[locale]/*.json"]
    },
  },
}

Feel free to customise the gt.config.json file to suit your needs. See the configuration docs for more information.

Update the json file format so that the include path matches your project structure.

Translations will preserve the original string syntax.

Step 4: Add the gtx-cli translate command to your build process

Add the gtx-cli translate command to your build or CI process before the build command to automatically add translations to your project.

package.json
{
  "scripts": {
    "translate": "npx gtx-cli translate",
    "build": "npm run translate && <your build command>"
  }
}

This will generate translations for all your locales and save them to your project. If you want to commit these files to your repo, you can run this command beforehand.

You’re done! Your project will now automatically update all your translation JSON files whenever your project changes.


Notes

  • You can automatically add translations to your project with the gtx-cli translate command.
  • If you want to commit your translation files, you should run the gtx-cli translate command before committing.
  • To configure the output path for your translations, see the configuration docs.

Next steps

How is this guide?

JSON