How to translate JSON files

How to translate JSON files: guide to l10n & i18n with examples

What is JSON? A regular guy might reply that it’s the name of a popstar. Not to say we’re irregular, but for us developers, surely that word instead evokes a lifesaving format simplifying our web application’s data transmissions. As a data interchange format that has risen above all others and stayed at the top even to this day, we thought JSON deserved its own article exploring how it helps with the much-needed concept of l10n (localization) and we will also show you how to translate JSON files.

So, without further ado, let’s see how the seemingly simple JSON format plays a genuinely pivotal part in making JavaScript project l10n much easier to maneuver!

We will cover the following topics in this tutorial:

  • JSON l10n (localization)/i18n (internationalization) and how to translate JSON files.
  • A step-by-step walkthrough explaining how a simple JavaScript & jQuery application can perform localizations through JSON.
  • Manually adding JSON language resource files as hardcoded JSON strings or by importing JSON files.
  • How JSON file l10n can take place via REST API requests sent to the Google Cloud Translation API.
  • Using the toJSON method and JavaScript template literals to deal with placeholders.
  • Ways to perform pluralization in multiple localizations using the “gettext.js” library.
  • An introduction to JSON formats supported by Lokalise.

    Assumptions

    Basic knowledge of:

    • JSON
    • JavaScript
    • jQuery library

    Prerequisites

    A local environment set up with:

    • JavaScript-supported IDE.
    • JavaScript-enabled browser.

    Environment

    I will be using the following environment for my development purposes:

    • WebStorm 2019.1.2 Build #WS-191.7141.49
    • Firefox 92.0 (64-bit)

    The source code is available on GitHub.

    A simple JavaScript project to localize later on

    What’s the point of a JSON—or, in other words, a JavaScript Object Notation—file if it doesn’t have a JavaScript application in which to bloom?

    Firstly, let’s launch our IDE and make a JavaScript project named JsonL10n inside an identically named folder.

    Secondly, let us create the default page of our JsonL10n application by adding an index.html file to the project:

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>JSON L10n</title>
    </head>
    <body>
    
    </body>
    </html>

    Note: If you’re using WebStorm, you can type “!” and press Tab to easily generate this script.

    Thirdly, we must remember to add the jQuery library to our project:

    1. Download the jQuery library .js file from the jQuery website.
    2. Place the downloaded library file inside the JsonL10n app’s root directory.
    3. Load the script in the <head> tag of the JsonL10n project’s index.html file:
    <head>
        .
        < script src="jquery-3.6.0.min.js"></script>
    </head>

    You may also be interested in How to localize vanilla Javascript apps with jQuery.i18n

    Time to translate JSON

    It’s showtime! We created a basic JavaScript project and loaded the jQuery library inside it. Now, it’s time to put our own guinea pig, the JsonL10n app, to the test with some localization-related JSON scenarios.

    Manually add JSON language resources 

    Before we enlist the help of any other service or library for our localization purposes, let’s step into JSON l10n, writing our JSON strings ourselves.

    Use hardcoded language resources

    So as our first move, we’ll add a JSON string holding multiple language resources into our JsonL10n project.

    Firstly, we will head over to our JsonL10n project’s index.html file and add a JavaScript JSON string in its <head> tag:

    <script>
        let langResourcesArr = {
            "en": {
                "hello" : "Hello!",
                "welcome": "Welcome to my app!"
            },
            "fr": {
                "hello": "Bonjour!",
                "welcome": "Bienvenue sur mon appli!"
            },
            "it": {
                "hello": "Ciao!",
                "welcome": "Benvenuto nella mia app!"
            }
        };
    </script>

    Secondly, let’s add a few HTML elements to the <body> of the index.html file to display our localizations:

    <button id="fr" class="lang-choice" onclick="changeLanguage(this.id)">French</button>  <!-- 1 -->
    <button id="it" class="lang-choice" onclick="changeLanguage(this.id)">Italian</button>  <!-- 2 -->
        
    <ul id="greetings-list">  <!-- 3 -->
        <li class="greet" key="hello">Hello!</li>
        <li class="greet" key="welcome">Welcome to my app!</li>
    </ul>
    1. A button with the class “lang-choice” and id “fr” holds a value of “French”. Upon clicking the button, a changeLanguage function is called, passing its id as a parameter value.
    2. A button with the class “lang-choice” and id “it” holds a value of “Italian”. Upon clicking the button, a changeLanguage function is called, passing its id as a parameter value.
    3. An unordered list with the id “greetings-list” holds two list items with the class “greet”. Each list item holds a custom attribute of “key” to identify its content.

    Thirdly, let’s code this missing changeLanguage function that the buttons in the previous sections seem to call, shall we?

    We will implement this code in the same <script> tag holding the declaration of our langResourcesArr JSON string in the <head> tag:

    <script>
        .    
        function changeLanguage(clickedLangChoiceId) {  // 1
                $(function() {  // 2
                    $("#greetings-list").children(".greet").each(function() {  // 3
                        let currentlyIteratedGreetKey = $(this).attr("key");  // 4
                        let localizedValForGreetKey = langResourcesArr[clickedLangChoiceId][currentlyIteratedGreetKey];  // 5
                        $(this).text(localizedValForGreetKey);  // 6
                    });
                });
        }
    </script>
    1. Declare the changeLanguage function accepting a clickedLangChoiceId as an argument.
    2. Shorthand for jQuery’s $(document).ready() function. This is placed to make our changeLanguage function wait until all elements on the page are loaded before it executes.
    3. Traverse the children with class “greet” in a list of id “greetings-list”.
    4. Extract a “key” attribute value from the currently iterated list item. The extracted value is saved in a currentlyIteratedGreetKey variable.
    5. Access the langResourcesArr JSON string’s JSON object holding a clickedLangChoiceId key. In this JSON object, find the key-value pair with the currentlyIteratedGreetKey key and pass its value to a localizedValForGreetKey variable.
    6. Change the currently iterated list item’s text to the value in localizedValForGreetKey.
    Test it out

    That’s it! Running our JsonL10n project will let us localize the greeting messages to both the French and Italian locales!

    French locale:

    Italian locale:

    Import language resources from JSON file

    Why clutter our JsonL10n project’s HTML files when we can place our language resource-holding JSON files separately? Let’s see how we can set this up.

    Firstly, we’ll create a “lang” directory within our JsonL10n project, and place an fr.json file inside it:

    {
      "hello": "Bonjour!",
      "welcome": "Bienvenue sur mon appli!"
    }

    As you can see, we’ve put our French locale language resources inside it.

    Similarly, let’s not forget to add an “it.json” file as well, to hold the Italian locale counterparts:

    {
      "hello": "Ciao!",
      "welcome": "Benvenuto nella mia app!"
    }

    Now, let’s make a simple change to the HTML buttons we previously added inside the <body> of our index.html file:

    <button id="fr" class="lang-choice" onclick="changeLanguageUsingLangResOnExternalJson(this.id)">French</button>
    <button id="it" class="lang-choice" onclick="changeLanguageUsingLangResOnExternalJson(this.id)">Italian</button>

    Evidently, the buttons stay exactly the same as last time; except in this instance, a changeLanguageUsingLangResOnExternalJson function is called at the click of each button. When the button is clicked, its id is passed to the changeLanguageUsingLangResOnExternalJson function as an argument.

    Lastly, as you might have guessed, it’s time to code that changeLanguageUsingLangResOnExternalJson function!

    Just like last time, let’s code this function within the <script> tag inside the index.html file’s <head> tag:

    <script>
        .
        function changeLanguageUsingLangResOnExternalJson(clickedLangChoiceId) {  // 1
            $(function() {
                $.getJSON("lang/" + clickedLangChoiceId + ".json", function(jsonData) {  // 2
                    $("#greetings-list").children(".greet").each(function() {  // 3
                        let currentlyIteratedGreetKey = $(this).attr("key");  // 4
                        let localizedValForGreetKey = jsonData[currentlyIteratedGreetKey];  // 5
                        $(this).text(localizedValForGreetKey);  // 6
                    });
                });
            });
        }
    </script>
    1. Declare the changeLanguageUsingLangResOnExternalJson function accepting a clickedLangChoiceId as an argument.
    2. Use the jQuery.getJSON method to retrieve the locally saved JSON language resource file named as the value in clickedLangChoiceId. jQuery.getJSON passes the retrieved JSON object as a jsonData parameter to its callback function.
    3. Traverse the children with class “greet” in a list with the id “greetings-list”.
    4. Extract a “key” attribute value from the currently iterated list item. The extracted value is saved in a currentlyIteratedGreetKey variable.
    5. Access currentlyIteratedGreetKey on the jsonData JSON object and pass its value to a localizedValForGreetKey variable.
    6. Change the currently iterated list item’s text to the value in localizedValForGreetKey.
    Test it out

    That wasn’t so hard, was it? Running our JsonL10n application will give us the exact same results as before. But, this time, the language resources aren’t hardcoded to the index.html file. In other words, our JsonL10n app’s language resources aren’t tightly coupled with its code anymore!

    Translate JSON via REST API requests

    In both the instances we explored earlier, we relied on locally stored JSON code or JSON files for our l10n efforts. But imagine a situation like this: Assume our JsonL10n application plans to provide real-time, worldwide updates for the Olympics localized to the users’ locales. This brings two major challenges to the project:

    • Localizations need to be quick and adaptive. We can’t have missing words in our language resources since we can’t make our users wait until a new word gets localized.
    • Widespread localizations are required. We can’t simply localize our JsonL10n app to one or two languages and call it a day if we plan for our app to reach the whole world. Instead, we’d need to localize our app to hundreds of languages.

    We believe you’d agree that the most convenient way to overcome these challenges would be to delegate the localization resource-providing job to an external service.

    Meet Google Cloud Translation

    Let’s uncover how to send a REST request holding a JSON language resource file to the Google Cloud Translation API and retrieve a localized JSON language resource file.

    Before we can use their service, the Cloud Translation API asks us to perform a few initial tasks to get set up.

    Firstly, we would need a Google Cloud project to create, enable, and use the Cloud Translation API. Let’s create one per the steps mentioned in their documentation.

    Secondly, we require a Google Cloud Billing account that manages any costs relating to our usage of the Cloud Translation API functions. Don’t get thrown off by “billing,” since the Cloud Translation API Basic version we plan to use is free for the first 500,000 characters. We can use the guide Google conveniently provides for this purpose.

    Thirdly, it’s time to enable the Cloud Translation API. Let’s head over to the Cloud Translation API homepage and enable it for our Google Cloud project.

    Fourthly and finally, we should create an API key for authorization purposes. Let’s follow the steps mentioned in the Google Cloud documentation to create an API key for our Google Cloud project.

    Important note: Make sure to take note of this key since we will require it to gain access to Cloud Translation API services later on.

    Time to use the Cloud Translation API

    Now that we’re finally done setting up the API, it’s about time we put it to good use, don’t you think?

    So firstly, let’s add a new “googleTranslate.js” file to our JsonL10n project and initially place our API key inside it as a constant:

    const apiKey = "your-cloud-translation-api-key-here";

    Secondly, let us add a localize function inside our “googleTranslate.js” file:

    function localize(targetLang, inputToLocalize) {
        let url = "https://translation.googleapis.com/language/translate/v2";  // 1
        url += "?key=" + apiKey; // 2
        url += "&q=" + inputToLocalize;  // 3
        url += "&target=" + targetLang;  // 4
    
        return $.ajax({  // 5
            url: url,
            type: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            success: function(localizedResponse) { // 6
                let localizedJsonStr = localizedResponse.data.translations[0].translatedText;  // 7
                let decodedLocalizedJsonStr = decodeHTML(localizedJsonStr);  // 8
    
                downloadLocalizedLangResourceJsonFile(targetLang, decodedLocalizedJsonStr);  // 9
            }
        });
    }
    1. Set the Google Cloud Translation API request URL inside a url variable.
    2. Pass the Cloud Translation API key as a key parameter value in the URL.
    3. Pass the inputToLocalize value inside a q parameter in the URL.
    4. Pass the targetLang value inside a target parameter in the URL.
    5. Send an asynchronous POST request holding the JSON to be localized over to the Google Cloud Translation API.
    6. Upon the AJAX request’s success, a callback function is called, carrying the response JSON object in a localizedResponse variable.
    7. Extract the localized JSON Object from the response and save it in a localizedJsonStr variable.
    8. Decode localizedJsonStr using a decodeHTML function and place it in a decodedLocalizedJsonStr variable.
    9. Call a downloadLocalizedLangResourceJsonFile function passing both targetLang and decodedLocalizedJsonStr to it as parameters.
    Add missing functions

    As you might have noticed, our code has two unresolved functions for the time being. Let’s add them before our IDEs go bananas!

    So thirdly, let’s place a decodeHTML function in our JsonL10n project’s “googleTranslate.js” file:

    function decodeHTML(encodedStr) {
        let textArea = document.createElement("textarea");  // 1
        textArea.innerHTML = encodedStr;  // 2
        return textArea.value;
    }
    1. Create an HTML textarea element and store it in a textArea variable.
    2. Fill the textArea element with the encodedStr, in turn automatically decoding its HTML characters.
    3. Return the value stored in textArea.

    Fourthly, let’s code the remaining undefined function. We’ll add a downloadLocalizedLangResourceJsonFile function in the “googleTranslate.js” file:

    function downloadLocalizedLangResourceJsonFile(localizedLang, jsonStr) {
        const blob = new Blob([jsonStr], {type : 'application/json'});  // 1
        let referenceToBlob = URL.createObjectURL(blob);  // 2
    
        let linkToDownloadLocalizedJson = document.createElement('a');  // 3
        linkToDownloadLocalizedJson.setAttribute("href", referenceToBlob);  // 4
        linkToDownloadLocalizedJson.setAttribute("download", localizedLang + ".json");  // 5
        linkToDownloadLocalizedJson.click();  // 6
    }
    1. Create a blob with the MIME type “application/json” passing the jsonStr as a single value inside an array.
    2. Use URL.createObjectURL to create a reference to our blob and place it in a variable named referenceToBlob.
    3. Create an HTML link element using Document.createElement and store inside a linkToDownloadLocalizedJson variable.
    4. Set an “href” attribute in linkToDownloadLocalizedJson passing referenceToBlob as its value.
    5. Set a custom “download” attribute carrying the value of a JSON file name created by concatenating localizedLang with a “.json” postfix.
    6. Simulate a mouse click on linkToDownloadLocalizedJson element using HTMLElement.click.

    Fifthly, let us head back to our JsonL10n project’s “index.html” file and place a simple jQuery click event handler:

    <script>
        $(function() {
            $(".lang-choice").on("click", function() {  // 1
                let targetLang = $(this).attr("id");  // 2
                $.getJSON("lang/en_default.json", function(jsonData) {  // 3
                    localize(targetLang, JSON.stringify(jsonData));  // 4
                });
            });
        });
    </script>
    1. Attach a click event handler to HTML elements with the class “lang-choice” using a jQuery .on() function.
    2. Extract the currently clicked element’s “id” attribute and place it in a targetLang variable.
    3. jQuery.getJSON() obtains an “en_default.json” JSON language resource file saved inside the project’s “lang” directory. This retrieved object is passed as a jsonData parameter to its callback function.
    4. Call the localize function we previously coded, passing in targetLang and a jQuery stringified jsonData string as its parameters.
    Final touches

    Let’s finish up our Google Cloud Translation procedure with a few little additions and changes.

    Firstly, we’ll add an “en_default.json” file in our JsonL10n project’s “lang” directory:

    {
      "hello": "Hello!",
      "welcome": "Welcome to my app!"
    }

    As you can see, this JSON file simply holds the default language resources with an English language l10n. Now, the Cloud Translation API can use this file as input to perform its localization to multiple languages.

    Secondly, we must remember to remove the “onclick” handlers from our HTML elements of class “lang-choice” just to avoid any unnecessary functions calls.

    <button id="fr" class="lang-choice">French</button>
    <button id="it" class="lang-choice">Italian</button>
    Test it out

    So, fingers crossed! If all went well, when clicking either one of the languages, our JsonL10n app should swiftly provide us with a parsed and ready JSON file localized to our language of choice.

    French locale:

    Italian locale:

    As you can see, we have received the JSON files holding the expected l10n right into our hands. And this time, we didn’t even create a JSON file, let alone write a single word of one, when performing our JSON localizations!

    Some JSON l10n extras

    Alright, we’ve learned how to translate JSON file both locally and using an external translation service. But before concluding, why not learn a few extras we just might need in our JSON ventures?

    Placeholder usage

    Let’s assume our JsonL10n app plans to maintain custom JSON language resource files for all of its users. As usual, the app would greet the user with a localized “Hello!” message; but, since we will maintain the user’s own JSON file, surely we could go beyond a generic same-for-all “Hello” message, am I right?

    Hence, let’s find out how we can ask the user for their name and their choice of language, and store a custom JSON language resource file just for them!

    Add greeting choices

    Firstly, we will head over to the JsonL10n project’s “index.html” and add the following in its HTML <body>:

    <label id="type-name">Please input your name: </label>
    <input type="text" id="name-input">
    <button class="name-submit" choice="en">Greet me in English</button>
    <button class="name-submit" choice="fr">Greet me in French</button>
    <button class="name-submit" choice="it">Greet me in Italian</button>

    Accordingly, we have placed an HTML label followed by an input to request the user’s name. Afterward, the user is presented with a choice of three buttons where he or she can choose in what language they’d like to be greeted in.

    Code and handle the placeholder

    Secondly, it’s time to place a code inside the “index.html” to handle this user input:

    <script>
        $(function() {
            $(".name-submit").on("click", function() {  // 1
                let targetLang = $(this).attr("choice");  // 2
                let nameInput = $("#name-input").val();  // 3
                $.getJSON("lang/en_default.json", function(jsonDataObj) {  // 4
                    jsonDataObj.toJSON = function() {  // 5
                        return {
                            hello: `Hello ${nameInput}!`,  // 6
                            welcome: this.welcome  // 7
                        };
                    };
    
                    localize(targetLang, JSON.stringify(jsonDataObj));  // 8
                });
            });
        });
    </script>
    1. Attach a click event handler to HTML elements with the class “name-submit” via the jQuery .on() method.
    2. Extract a “choice” attribute from the currently clicked button with the “name-submit” class. A targetLang variable is initialized with that extracted value.
    3. Initialize a nameInput variable with the user input value in the text input element with the id “name-input”.
    4. Load the “en_default.json” file in the JsonL10n project’s “lang” directory using the jQuery getJSON() method. Once successfully loaded, the getJSON method’s callback function gets called with the opened JSON object passed as a jsonDataObj argument.
    5. Set the jsonDataObj object’s toJSON() method to return a custom JSON object when JSON.stringify() is called.
    6. Set a JavaScript template literal including a ${nameInput} placeholder as the JSON value for the “hello” key. Now, whenever a JSON.stringify() method is called on jsonDataObj, the placeholder value will be filled with the nameInput value obtained from the user.
    7. Leave the “welcome” key as is. Hence, the JSON.stringify() method will load the same value that’s already in the “en_default.json” file for the “welcome” key’s value.
    8. Call the localize function in the “googleTranslate.js” file with the user-chosen targetLang as its first parameter. Then, JSON.stringify() method is called, passing in jsonDataObj for its argument and the returned value is passed over as the second parameter for the localize function call.

    Test it out

    Thus, running our JsonL10n app will show an additional line, like so:

    Entering a name and clicking a given choice of language will download a JSON file that holds a nicely localized and personalized greeting!

    English locale:

    French locale:

    Italian locale:

    Pluralize in multiple locales

    Imagination time! This time around, our JsonL10n app serves for an apple farm—yes, the physical kind. Assume that our application maintains a JSON file with an array containing the number of apples picked in a day. And, that our app lets the user retrieve these apple quantities and print them in multiple languages. Let’s see how we can implement this, shall we?

    Before anything else, let’s introduce an “apple_quantities.json” file to our project’s “lang” directory just to hold some arbitrary apple counts:

    {
      "picked": [22, 0, 12, 1, 15, 1, 16, 0, 1, 34]
    }

    Since neither JavaScript nor jQuery provides native support for pluralization, we’ll have to resort to a 3rd party library for this purpose.

    Say hello to Gettext.js

    Gettext.js is simply a JavaScript port of the ever popular and decades-matured GNU gettext. Let us find out how to use it for our localized pluralizations!

    Set up gettext.js for a default locale
    Make HTML changes

    Firstly, let’s open the index.html file and add some HTML elements in the page’s body:

    <label>Please choose language to list the picked up apple quantities: </label>
    <button class="apples-lang-submit" choice="en">Apple quantity in English</button>  // 1
    <br><textarea id="apple-quantities-list" rows="10"></textarea>  // 2
    1. Add an HTML button with the class “apples-lang-submit” holding a custom attribute “choice” with a value of “en”.
    2. Set an HTML textarea right below the buttons with an id of “apple-quantities-list” and its row count set to 10.

    Secondly, let’s introduce the gettext.js library to our JsonL10n project:

    1. Download the Gettext.js library’s “.zip” or “.tar.gz” file from its official site.
    2. Extract the gettext.js file from the downloaded file’s “bin” directory and place it in the JsonL10n project’s root directory.
    3. Open the gettext.js file copied to the JsonL10n project and remove or comment out the export statement in its last line:
    .
    // export default i18n;

    Note: This measure is taken since we will be using the gettext.js library as a vanilla JS instead of as a JavaScript module in our JsonL10n project.

    1. Load the gettext.js script inside the “index.html” file by placing this in its HTML:
    <head>
        .
        < script src="gettext.js" type="text/javascript"></script>
    </head>
    1. Use the jQuery.getJSON method to retrieve the “apple_quantities.json” file. jQuery.getJSON passes the retrieved JSON object as an appleQuantitiesJsonObj parameter to its callback function.
    2. Extract the JSON array with a key of “picked” from appleQuantitiesJsonObj and save it in an appleQuantitiesArr variable.
    3. Empty the content in the HTML textarea with an id of “apple-quantities-list”.
    4. Iterate the content in appleQuantitiesArr using JavaScript forEach method. The callback function holds the currently iterated value of appleQuantitiesArr as a variable named currentQuantity. Call the ngettext function of the gettext.js library passing in the singular form, plural form, and quantity parameters as its parameters. As a direct port of GNU gettext, the ngettext method of the gettext.js library called here conforms to the same rules and behaviors as the GNU gettext utility’s ngettext method. The value returned from the ngettext method is appended to the HTML textarea with an id of “apple-quantities-list”.
    Test it out

    Let’s run our JsonL10n app and click the “Apple quantity in English” button. As expected, the HTML textarea is filled with the correctly pluralized counts of apples that were picked!

    Configure gettext.js for an additional locale

    Well, what if our apple farm hired a new manager and he only speaks French? Let’s see how we can add a few changes to our JsonL10n app so that the app can display the apple count in the French locale in addition to its default English locale.

    Firstly, we’ll head over to our JsonL10n project’s “index.html” file and add the missing HTML button in its <body>:

        <button class="apples-lang-submit" choice="fr">Apple quantity in French</button>

    This line adds an HTML button with the class “apples-lang-submit”, holding a custom attribute of “choice” with a value of “fr”.

    Note: Make sure to place this button right next to the English locale button just to make things easy on the eye!

    Secondly, let’s add the highlighted code snippet to the previously coded “apples-lang-submit” class click event handler:

    <script>
        $(function() {
            $(".apples-lang-submit").on("click", function () {
                let targetLang = $(this).attr("choice");
    
                if (targetLang === "fr") {  // 1
                    $.getJSON("lang/apple_count_fr.json", function(json) {  // 2
                        gettext.loadJSON(json);  // 3
                    });
                }
    
                gettext.setLocale(targetLang);
                displayAppleQuantities();
            });
        });
    </script>
    1. Check if the currently clicked button with the class “apples-lang-submit” holds a “choice” attribute value of “fr” locale.
    2. Load an “apple_count_fr.json” file inside the “lang” directory using the jQuery.getJSON method. jQuery.getJSON passes the loaded JSON object as a json parameter to its callback function.
    3. Call gettext.js library’s loadJSON method passing in the json object as its parameter argument.

    Thirdly, let’s place an “apple_count_fr.json” file inside our JsonL10n project’s “lang” directory:

    {
      "": {
        "language": "fr",
        "plural-forms": "nplurals=2; plural=n>1;"
      },
      "Welcome": "Bienvenue",
      "%1 apple picked": [
        "%1 pomme cueillie",
        "%1 pommes cueillies"
      ]
    }
    

    This file follows the JSON format desired by the gettext.js library to hold singular and plural forms for the French locale.

    Test it out

    Let’s run our JsonL10n application again to test if the changes are visible:

    This time around, we can display the picked apple quantities perfectly pluralized to multiple localizations. Don’t be afraid to add, remove, or change the values in the “apple_quantities.json” file to see the results with a simple reload of the browser page!

    Note: Due to JSON file loading delays, an initial click on the “Apple quantity in French” button right after a page load might not present the values localized to the French locale. But, sure enough, things will work from the next click onward!

    Translate JSON files with Lokalise

    As we’re closing in on the end of the article, you might have been surprised at one time or another at what a mostly overlooked and taken-for-granted data interchange format JSON brings to the table in terms of l10n. And don’t forget, we only explored JSON at a basic HTML, JavaScript, and jQuery level. Loads of other programming languages—both front-end and back-end—hold their own initiatives for dealing with JSON, bringing an additional layer of complications to address.

    Well, what if I told you there’s a way easier, a savior of a platform that takes care of all your JSON l10n-related concerns on any and all of the programming languages?

    Meet Lokalise, the translation management system that oversees all your JSON localization needs with features like:

    • Easy integration with various other services.
    • Collaborative translations.
    • Quality assurance tools for translations.
    • Easy management of your translations through a central dashboard.
    • Plus, loads of others.

    Translate JSON with ease!

    Your JSON served structured or regular, Sir?

    Lokalise lets you import and export JSON files in two forms:

    • Structured JSON files: Lokalise lets you manage your project’s localization-related JSON files in a structured (predictable) and non-nested manner.
    • Regular JSON files: Have no worries if structured isn’t your cup of tea. Lokalise surely supports the good old flat and nested JSON files, all the same!

    Start with Lokalise in just a few steps:

    • Sign up for a free trial (no credit card information required).
    • Log in to your account.
    • Create a new project under any name you like.
    • Upload your translation files and edit them as required.

    Done! Finito! You have already completed the baby steps toward Lokalise-ing your JSON-wielding web application. See the Getting Started section for a collection of articles that will provide all the help you’ll need to kick-start the Lokalise journey. Also, refer to Lokalise API Documentation for a complete list of REST commands you can call on your Lokalise localization/internationalization project.

    Conclusion

    In this tutorial, we dived into a JSON-focused step-by-step guide to the l10n of a JavaScript application. We explored how JSON—be it hardcoded in the app, imported as a file, or exported for a 3rd party service to translate—could showcase some spectacular desirability in the world of l10n.

    As a few extras, we also managed to set placeholders on JSON files with the help of the JavaScript toJSON method and perform pluralization on multiples locales using the gettext.js library.

    Hence, my time has come, son. You may go and JSON. Drop me a line if you have any questions, and don’t hesitate to leave a comment.

    Until next time, put on some Jason you-know-who’s songs in the background, and just trumpet your way into JSON l10n!

    Related posts

    Learn something new every two weeks

    Get the latest in localization delivered straight to your inbox.

    Related articles
    Localization made easy. Why wait?
    The preferred localization tool of 2000+ companies