What the script does
- Flatten nested JSON into
key.pathand value pairs. - Batch the values: at most 50 strings and well below 50,000 characters per request.
- Translate each batch with one call to
POST /v1/translate. - Validate that placeholders such as
{name},{{count}}and%sare unchanged. If not, keep the source text and warn. - Write the target file with the original structure.
The script
Requires Node.js 18 or newer. Save it as translate-json.mjs, set GLOSSFERRY_API_KEY and run node translate-json.mjs en.json DE.
// translate-json.mjs
import { readFile, writeFile } from 'node:fs/promises';
const [, , sourcePath, target] = process.argv;
const API = 'https://api.glossferry.com/v1/translate';
const flatten = (obj, prefix = '', out = {}) => {
for (const [k, v] of Object.entries(obj)) {
const key = prefix ? `${prefix}.${k}` : k;
if (v && typeof v === 'object') flatten(v, key, out);
else out[key] = String(v);
}
return out;
};
const unflatten = (flat) => {
const out = {};
for (const [key, value] of Object.entries(flat)) {
key.split('.').reduce((o, part, i, parts) => (o[part] ??= i === parts.length - 1 ? value : {}), out);
}
return out;
};
// {name}, {{name}} and %s / %d placeholders, compared as a sorted list
const placeholders = (s) => (s.match(/\{\{[^}]+\}\}|\{[^}]+\}|%[sd]/g) ?? []).sort().join('|');
async function translate(texts) {
const res = await fetch(API, {
method: 'POST',
headers: { Authorization: `Bearer ${process.env.GLOSSFERRY_API_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ text: texts, target_lang: target, source_lang: 'EN' }),
});
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
return (await res.json()).translations.map((t) => t.text);
}
const flat = flatten(JSON.parse(await readFile(sourcePath, 'utf8')));
const result = {};
let batch = [];
let chars = 0;
async function flush() {
if (!batch.length) return;
const out = await translate(batch.map((k) => flat[k]));
batch.forEach((k, i) => {
const ok = placeholders(flat[k]) === placeholders(out[i]);
result[k] = ok ? out[i] : flat[k]; // fall back to the source text and flag it
if (!ok) console.warn(`placeholder mismatch, kept source text: ${k}`);
});
batch = [];
chars = 0;
}
for (const key of Object.keys(flat)) {
if (batch.length >= 50 || chars + flat[key].length > 40000) await flush();
batch.push(key);
chars += flat[key].length;
}
await flush();
await writeFile(`${target.toLowerCase()}.json`, JSON.stringify(unflatten(result), null, 2) + '\n');
console.log(`Wrote ${target.toLowerCase()}.json with ${Object.keys(result).length} strings`);
Keys that contain a dot in their name will not round-trip with this simple flattening. Use another separator if yours do.
The same call in Python
import os, requests
def translate(texts, target, source="EN"):
r = requests.post(
"https://api.glossferry.com/v1/translate",
headers={"Authorization": f"Bearer {os.environ['GLOSSFERRY_API_KEY']}"},
json={"text": texts, "target_lang": target, "source_lang": source},
timeout=60,
)
r.raise_for_status()
return [t["text"] for t in r.json()["translations"]]
Tips for real projects
- Translate only what is missing. Compare the source and target files and send only new or changed keys. This is the biggest cost saver.
- Commit the output. Reviewers can then see exactly what changed in each language.
- Keep a review step. Have a native speaker check the screens with the most traffic and the legal ones.
- Handle errors. A
402means the balance is empty, a429means you hit the rate limit, a502means the backend failed and nothing was charged. See the error list.
What it costs
A file with 2,000 strings of about 45 characters has 90,000 characters, which is EUR 1.08 per language at EUR 12.00 per million. More examples are in the pricing models guide.