How to Extract Translatable Strings from Static HTML Into JSON and Rebuild Clean Markup
Use data-i18n keys and an HTML parser to extract translatable strings into a flat JSON catalog, then rebuild each locale from the same source document. The technique covers visible text and selected accessibility attributes; the production caveat is that a parser preserves the document structure, not the original formatting or byte sequence.
Keep the source HTML in version control, give translators JSON rather than markup, and write each localized page to a separate path. Use keys that describe a string’s purpose instead of its wording or position. The build should stop if a key is missing, an old key is still present, or a text marker contains markup the script can’t safely replace.
Mark translation units in the source HTML
<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title data-i18n="billing.title">Billing help</title>
</head>
<body>
<main>
<h2 data-i18n="billing.heading">Invoices & receipts</h2>
<a href="/support" data-i18n="billing.help"
data-i18n-fields="text title" title="Open billing support">Get billing help</a>
<img src="/assets/divider.svg" alt="">
<p translate="no">Northwind</p>
</main>
</body>
</html>
Save this example as billing.html. Without data-i18n-fields, the marker selects text only; the explicit list on the link selects both its label and its title. The extractor reads the decoded heading as Invoices & receipts, while the link destination, decorative image, and brand name stay outside the catalog.
Never send URLs, IDs, class names, merge tags, or JavaScript to a translator as plain editable strings. If a link destination needs to change by locale, resolve it from a separate route map rather than a copy catalog.
Choose what goes into the catalog
| Content | Source marker | JSON result |
|---|---|---|
| Plain visible text or document title | data-i18n="billing.heading" | "billing.heading": "Invoices & receipts" |
| Visible text and a tooltip | data-i18n="billing.help" data-i18n-fields="text title" | billing.help and billing.help@title |
| Accessible name for an icon-only control | data-i18n="dialog.close" data-i18n-fields="aria-label" | dialog.close@aria-label |
| Decorative image | alt="", with no translation marker | No entry; retain the empty alternative |
| Structural attribute | href="/support", with no field for href | No entry; retain the destination |
The script also accepts alt and placeholder for nonempty source strings. Mark an informative image’s alternative text, but leave a decorative image’s alt="" alone. If you translate a placeholder, translate the field’s visible label separately; the placeholder is not a substitute for a label.
Keep a key when you edit the wording without changing its purpose. Assign a new key when the message takes on a different meaning, even if the English text stays the same. Two buttons that both say Open may need different translations if one opens a document and the other reopens a support case.
Keep each sentence available as one unit
<!-- Broken: the marker contains both a text node and an element. -->
<p data-i18n="receipt.notice">Keep your <strong>receipt</strong> for your records.</p>
<!-- Fixed when the emphasis is optional: mark one complete sentence. -->
<p data-i18n="receipt.notice">Keep your receipt for your records.</p>
The first example is valid HTML, but the extractor rejects it rather than dropping the emphasis or turning the tag into a string. The second keeps the whole sentence available for reordering in translation. When the inline element carries meaning or functionality, such as a link inside a sentence, use a separate rich-message format with validated movable placeholders instead of stripping the element.
Never split a sentence into separate keys just because a word is bold or linked. Translators need to be able to move the emphasized or linked phrase to the position the target language requires.
Extract and rebuild with a single Python script
The script uses Beautiful Soup with the html5lib parser so the source is read as an HTML document rather than matched with regular expressions. It accepts UTF-8 files, rejects duplicate keys, and creates a new destination file without overwriting an existing file.
# localize_html.py
import argparse
import json
import re
from pathlib import Path
from bs4 import BeautifulSoup, NavigableString
KEY = re.compile(r"[a-z][a-z0-9_-]*(?:\.[a-z0-9_-]+)*")
LANG = re.compile(r"[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*")
FIELDS = {"text", "alt", "title", "aria-label", "placeholder"}
HTML_NS = "http://www.w3.org/1999/xhtml"
EXCLUDED = {
"script", "style", "template", "noscript", "textarea", "iframe",
"xmp", "noembed", "noframes", "plaintext",
}
def parse_args():
parser = argparse.ArgumentParser(description="Localize marked static HTML.")
modes = parser.add_subparsers(dest="mode", required=True)
for mode in ("extract", "build"):
command = modes.add_parser(mode)
command.add_argument("source", type=Path)
command.add_argument("destination", type=Path)
if mode == "build":
command.add_argument("--catalog", type=Path, required=True)
command.add_argument("--lang", required=True)
command.add_argument("--dir", choices=("ltr", "rtl"), required=True)
return parser, parser.parse_args()
def collect(soup):
entries = {}
marked = soup.select("[data-i18n], [data-i18n-fields]")
used = set()
for tag in marked:
base = tag.get("data-i18n", "")
if not KEY.fullmatch(base) or base in used:
raise ValueError(f"Invalid or repeated data-i18n key: {base!r}")
used.add(base)
lineage = [tag, *tag.parents]
if any(
node.name in EXCLUDED
or (node.namespace is not None and node.namespace != HTML_NS)
for node in lineage
):
raise ValueError(f"{base}: unsupported HTML context")
for node in lineage:
mode = node.get("translate")
if mode is None:
continue
mode = mode.lower()
if mode == "no":
raise ValueError(f"{base}: inside translate=no")
if mode in ("", "yes"):
break
fields = tag.get("data-i18n-fields", "text").split()
if not fields or len(set(fields)) != len(fields) or set(fields) - FIELDS:
raise ValueError(f"{base}: invalid data-i18n-fields")
for field in fields:
key = base if field == "text" else f"{base}@{field}"
if field == "text":
if len(tag.contents) != 1 or type(tag.contents[0]) is not NavigableString:
raise ValueError(f"{key}: expected one plain text node")
value = str(tag.contents[0])
else:
value = tag.get(field)
if not isinstance(value, str) or not value.strip():
raise ValueError(f"{key}: missing or blank source string")
entries[key] = (tag, field, value)
if not entries:
raise ValueError("No translation units found")
return entries, marked
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError(f"Duplicate JSON key: {key}")
result[key] = value
return result
def load_catalog(path, entries):
catalog = json.loads(
path.read_text(encoding="utf-8"), object_pairs_hook=unique_object
)
if not isinstance(catalog, dict):
raise ValueError("The catalog must be a JSON object")
missing = sorted(entries.keys() - catalog.keys())
extra = sorted(catalog.keys() - entries.keys())
if missing or extra:
raise ValueError(f"Catalog mismatch; missing: {missing}; extra: {extra}")
for key, value in catalog.items():
if not isinstance(value, str) or not value.strip() or "\x00" in value:
raise ValueError(f"{key}: expected a nonblank string without NUL")
return catalog
def main():
parser, args = parse_args()
try:
source = args.source.read_text(encoding="utf-8")
soup = BeautifulSoup(source, "html5lib")
entries, marked = collect(soup)
if args.mode == "extract":
catalog = {key: entry[2] for key, entry in entries.items()}
output = json.dumps(catalog, ensure_ascii=False, indent=2) + "\n"
else:
if not LANG.fullmatch(args.lang):
raise ValueError("Pass a language tag such as fr, fr-CA, or ar")
catalog = load_catalog(args.catalog, entries)
for key, (tag, field, _) in entries.items():
if field == "text":
tag.contents[0].replace_with(NavigableString(catalog[key]))
else:
tag[field] = catalog[key]
for tag in marked:
for attr in ("data-i18n", "data-i18n-fields"):
tag.attrs.pop(attr, None)
soup.html["lang"] = args.lang
soup.html["dir"] = args.dir
output = soup.decode(formatter="minimal")
payload = output.encode("utf-8")
with args.destination.open("xb") as destination:
destination.write(payload)
except (OSError, ValueError) as exc:
parser.exit(1, f"error: {exc}\n")
if __name__ == "__main__":
main()
The rebuild inserts catalog values as text or attribute values rather than parsing them as HTML, so a literal < in a translation doesn’t open a tag. The serializer can still normalize quoting, entities, or implied elements, so review structural changes rather than expecting a byte-for-byte diff. The language check catches malformed shapes such as fr_CA; supply a valid BCP 47 tag because the check doesn’t validate subtags against the registry.
Generate the catalog and build a locale
python -m pip install beautifulsoup4 html5lib
python localize_html.py extract billing.html billing.en.json
Run these commands from the directory containing the script and source page. Open billing.en.json and verify that it contains exactly the four intended strings, including billing.help@title but no URL or image alternative.
{
"billing.title": "Aide à la facturation",
"billing.heading": "Factures & reçus",
"billing.help": "Obtenir de l’aide sur la facturation",
"billing.help@title": "Ouvrir l’assistance à la facturation"
}
Save this as billing.fr.json, or copy the extracted catalog and edit only its values. Use a literal & character in JSON, not the HTML entity spelling &; the serializer will escape it at build time. Keep the English catalog available for review: a same-key English wording change won’t trigger a key mismatch, so it needs a source-value diff.
python localize_html.py build billing.html billing.fr.html \
--catalog billing.fr.json --lang fr --dir ltr
Always build from billing.html, not from a generated locale, because the generated file no longer has the extraction markers. Use a fresh output path or remove the previous generated artifact before rebuilding. For an Arabic locale, pass its catalog with --lang ar --dir rtl, then check components whose CSS assumes left-to-right positioning.
Validate the generated page before publishing
- Open
billing.fr.htmlin a browser and confirm that the tab title, heading, link text, and tooltip show the French copy. In source view, the heading should containFactures & reçus; on screen it should displayFactures & reçus. - Inspect the DOM for
lang="fr",dir="ltr", unchangedhref="/support", and no remainingdata-i18nordata-i18n-fieldsattributes. - Check the longest labels at narrow widths and in the accessibility tree. If the output is an email, send it through the delivery platform and check the received message, since post-processing can alter markup after the local build.
Use HTML Translate to compare a rendered locale with the source when checking copy in context.
Common mistakes and troubleshooting
- A heading fails with “expected one plain text node.” The marked element contains a child element, comment, or multiple nodes. Use a plain-text unit where appropriate or move the sentence to a rich-message workflow.
- The catalog reports an extra key after a rename. Re-extract from the current source and review the old and new keys before transferring translated values. Don’t bypass the mismatch by silently ignoring extra entries.
- An entity appears literally in the browser. A value was entered as
&in the JSON instead of&. Store characters in the catalog and let the serializer handle HTML escaping. - The wrong phrase becomes a screen reader label. Inspect the computed accessible name. A stale
aria-labelcan override visible text on a control, so translate it where it’s needed and remove redundant labels where appropriate. - An unchanged source phrase still appears in a locale. Check that it has a
data-i18nmarker and that the catalog value was actually translated. A key check can detect omitted entries, not untranslated values. - The rebuild refuses to write the destination. The script opens the destination in exclusive
xbmode. Use a new path or delete only the previously generated artifact and retry.
HTML File Translation Questions
Why not use the English text as the JSON key?
Copy edits would change the key, and identical English phrases could collide despite having different meanings. A key such as billing.help identifies the message independently of its current wording.
Can one element have both text and attribute translations?
Yes. Use a field list such as data-i18n-fields="text title". The plain text uses the base key, and the attribute uses the base key followed by @title.
Can translators add HTML to a JSON value?
No. The script serializes strings as text and attribute values. If a message needs markup, use a rich-message format that validates named placeholders and maps them back to trusted elements.
Will the generated page preserve every source line break?
No. html5lib builds a document tree, and serialization can change the source representation. Keep the original as the editable file and verify any whitespace-sensitive rendering in the browser or email client.
Does the root language setting replace nested language tags?
No. The build updates lang and dir on <html> only. Preserve intentional overrides on foreign-language passages, and audit any nested overrides that were added for the original locale.
Does this generate localized URLs or search metadata?
No. The script retains URLs and localizes only marked text or allowed attributes. Generate locale routes, canonical URLs, and hreflang links in the publishing layer, where the final URLs are known.
Related guides
- How to Translate HTML Files with Python (BeautifulSoup + DeepL or OpenAI API)
- How to Translate an HTML Email Template Without Breaking Merge Tags
- Translate HTML Without Breaking Layout: Checklist + Safe Workflow
The script and sample files from this article are on GitHub: localize_html.