I have a json document where some of the strings must be translated. For example (made-up syntax), my data.json:
{
"greeting": "trans:Hello"
}
In this case the string "Hello" is marked as translatable with the prefix trans: (which does not seem very robust). I would then use a tool to generate a catalog:
xgettext data.json
And then translate the strings to my target languages. My application will then use my original json and the translations mapping:
translations = {
"en" : {
"Hello": "Hello"
},
"es" : {
"Hello": "Hola"
}
}
And would generate the final json (for target language es):
{
"greeting": "Hola"
}
Is there any standard way of specifying translatable strings in json, so that they can be processed by standard tools to generate message catalogs?
You can use the appropriate gettext language preprocessor to extract strings which are marked, usually with _(string) or gettext(string), and create a gettext catalog (POT file) containing those strings. After you create a localized version of the catalog for a particular language, probably using a tool such as poedit, in this case you would then convert it into a JSON representation--for more information, and for ideas about standard ways to handle gettext-style message catalogs in JavaScript, take a look at JED--and then load this JSON-formatted catalog into your app at run-time, and access it via utilities defined for that purpose.
The notation _(string) has two effects. First, it marks the string for the extractor. Second, at run-time it invokes a function called _ to look up the string in the catalog and returns the localized value.
The problem with JSON is that obviously _(string) is invalid JSON syntax. If possible, consider changing this from a JSON file to a JS file containing an object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With