Translate JSON Files with On-Premise Machine Translation

Аnastasia Zhuk

Аnastasia Zhuk

Business Analyst, Linguist

Last Updated: June 30, 2026

At a Glance

  • Translate JSON files automatically while preserving structure, keys, placeholders, arrays, and formatting;
  • Use Lingvanex On-Premise Machine Translation for secure JSON localization inside your own infrastructure;
  • Implement JSON translation workflows in Python, JavaScript (Node.js/browser), or Bash;
  • Translate only text-based values while keeping non-text data types unchanged;
  • Validate translated JSON files to ensure compatibility with applications, APIs, and localization systems.
Translate JSON Files with On-Premise Machine Translation

Translating JSON files is not just about converting text from one language to another. For application localization, dataset translation, and multilingual product content, it is essential to preserve the original JSON structure, keys, nested objects, arrays, placeholders, numbers, booleans, and formatting. If these elements are changed during translation, the file may become invalid or break the application that depends on it.

Lingvanex On-Premise Machine Translation Software allows you to translate JSON content securely within your own infrastructure. While the software does not include a separate JSON localization feature, you can easily translate JSON files by extracting and translating only the text values inside the JSON structure, while keeping all technical elements unchanged.

In this guide, you’ll learn how to translate JSON files without breaking their structure using Lingvanex machine translation. We’ll walk through the process step by step and provide practical examples in Python, JavaScript, and Bash, so you can automate JSON translation for applications, datasets, and localization workflows.

Understanding the Translation Process

Translating a JSON file requires more than simply converting text from one language to another. The process must preserve the original JSON structure so the translated file remains valid and usable inside applications, APIs, localization systems, and datasets.

A typical JSON translation workflow includes the following steps:

  1. Reading the source JSON file;
  2. Parsing the JSON into a structure your programming language can process;
  3. Recursively traversing nested objects and arrays;
  4. Detecting and translating only text-based values;
  5. Preserving keys, placeholders, numbers, booleans, null values, and formatting;
  6. Rebuilding the JSON with translated content;
  7. Validating the translated JSON before deployment or use.

This approach allows developers to translate JSON files automatically while preserving structure, preventing broken formatting, and maintaining compatibility with existing applications and localization workflows.

Preparing Your JSON File

Before translating a JSON file, make sure it is valid and properly formatted. Even a small syntax error, such as a missing comma or quotation mark, can break the translation workflow or produce invalid output.

It is recommended to validate your JSON file with a JSON linter before starting the translation process. You should also verify the file path that will be used in your translation script.

For localization workflows, it is important to ensure that:

  • JSON keys remain unchanged;
  • Placeholders and variables are preserved;
  • Nested objects and arrays are valid;
  • Only translatable text values are processed.

Choosing Your Programming Environment

This guide includes examples in Python, JavaScript (Node.js), and Bash, allowing developers to integrate JSON translation into different environments and workflows.

Each programming language offers different advantages:

  • Python provides strong support for JSON processing, API integration, and automation;
  • JavaScript (Node.js) is ideal for web applications and modern localization pipelines;
  • Bash works well for lightweight command-line automation and server-side scripting.

The JavaScript example can be used not only in Node.js environments, but also in web browsers. However, browser-based execution does not support server-side file system operations such as fs.readFile(). In browser environments, JSON data should instead be loaded through file uploads, API requests, or other client-side methods.

Using the Lingvanex Translation API, you can automatically translate JSON files while preserving structure, keys, nested values, and formatting.

Python Implementation

This Python script does the following:

1. These lines import modules to work with JSON, check collection types, and send HTTP requests. In this example, we use the requests package to interact with the translation server. If it's not already installed in your system, run pip install requests before executing the script.

import json
from collections.abc import Mapping, Sequence
import requests

2. Here, we set the URL of the private translation server, the source language, the target language, and the path to the JSON file.

_PRIVATE_TRANSLATOR_URL: str = 'https://your-server-translator-url/api/translate'  # Translation server URL
_SOURCE_LANGUAGE: str = 'en'  # Source language
_TARGET_LANGUAGE: str = 'fr'  # Target language
_JSON_FILEPATH: str = '/path-to-your-json-file'  # Path to the JSON file

3. This function sends a request to the translation server with the text to be translated and returns the translated text. If the server returns an error, it will be handled.

def _translate(text: str) -> str:
    '''Translate text via private translator server'''
    request_body = {
        'source': _SOURCE_LANGUAGE,
        'target': _TARGET_LANGUAGE,
        'q': text,
    }
    with requests.post(url=_PRIVATE_TRANSLATOR_URL, data=request_body) as response:
        response.raise_for_status()  # In case of an error on the translator API side
        return response.json()['translatedText']
    def _translate_json_document(value: object) -> object:
        '''
        Recursively translates the object passed to this function.
        If the passed object is Mapping - translates only the values.
        :param value: One of the possible types that a JSON object can contain.
        '''
        if isinstance(value, str):
            return _translate(value)
    
        # Check if value is a List or a Dictionary and handle it appropriately
        if isinstance(value, Mapping):
            new_values = {}
            iterable_values = value.items()
        elif isinstance(value, Sequence):
            new_values = [None]*len(value)
            iterable_values = enumerate(value)
        else:
            return value
    
        for key, item in iterable_values:
            new_values[key] = _translate_json_document(item)
        return new_values
    

    5. This function reads the JSON file, parses and translates it using the previously defined functions, and prints the translated JSON to the console. The comments at the end of the function show how to save the translated JSON to a file if needed.

    def _main() -> None:
        with open(_JSON_FILEPATH, 'r') as json_file:
            data = json.load(json_file)  # Convert JSON to Python object
        translated = _translate_json_document(data)
        translated_json = json.dumps(translated, indent=4, ensure_ascii=False)
        print(translated_json)
    
        # Uncomment code below in case if you need to write translated JSON to file
    
        # target_translated_json_filepath: str = f'{_JSON_FILEPATH}.output.json'  # Replace with your filepath
        # with open(target_translated_json_filepath, 'w') as file:
        #     file.write(translated_json)
    

    6. This line runs the main function if the script is executed as the main module, rather than being imported by another module.

    if __name__ == '__main__':
        _main()
    

    JavaScript (Node.js) Implementation

    If you prefer JavaScript, here's how you can do it with Node.js:

    1. This line imports the fs (file system) module to work with files. We use promises for asynchronous operations.

    const fs = require('fs').promises;
    

    2. Here, we set the source language, target language, URL of the private translation server, and the path to the JSON file.

    const SOURCE_LANGUAGE = 'en'; // Source language
    const TARGET_LANGUAGE = 'fr'; // Target language
    const PRIVATE_TRANSLATOR_URL = 'https://your-server-translator-url/api/translate'; // Translation server URL
    const JSON_FILE_PATH = '/your-json-file-path'; // Path to the JSON file
    

    3. This function sends a request to the translation server with the text to be translated and returns the translated text.

    const translate = async (text) => {
        const requestBody = {
            'source': SOURCE_LANGUAGE,
            'target': TARGET_LANGUAGE,
            'q': text,
        };
        const options = {
            'method': 'POST',
            'headers': {'content-type': 'application/json'},
            'body': JSON.stringify(requestBody),
        };
        try {
            const response = await fetch(PRIVATE_TRANSLATOR_URL, options);
            const responseJson = await response.json();
            return responseJson['translatedText'];
        } catch (error) {
            throw new Error(`Translation failed: ${error.message}`);
        }
    };
    

    4. This function recursively translates all strings in the JSON object. If the value is a string, the function translates it. If it's an array or object, it processes them accordingly.

    const translateJsonDocument = async (value) => {
        if (typeof value === 'string') {
            return await translate(value);
        }
        if (value !== null && value !== undefined) {
            let entries, valueNew;
            if (Array.isArray(value)) {
                entries = value.entries();
                valueNew = [];
            } else if (typeof value === 'object') {
                entries = Object.entries(value);
                valueNew = {};
            }
            if (entries !== undefined) {
                for (const [key, item] of entries) {
                    valueNew[key] = await translateJsonDocument(item);
                }
                return valueNew;
            }
        }
        return value;
    };
    

    5. This function reads the JSON file, parses and translates it using the previously defined functions, and prints the translated JSON to the console.

    const main = async (jsonFilePath) => {
        try {
            const data = await fs.readFile(jsonFilePath, 'utf-8');
            const jsonObject = JSON.parse(data);
            const translated = await translateJsonDocument(jsonObject);
            const translatedJson = JSON.stringify(translated, null, 4);
            console.log(translatedJson);
        } catch (error) {
            console.error(`Error: ${error.message}`);
        }
    };
    

    6. This line runs the main function with the specified path to the JSON file.

    main(JSON_FILE_PATH);
    

    Bash Implementation

    For developers who prefer working directly in the terminal or integrating translation into shell scripts and automation pipelines, Bash provides a lightweight way to translate JSON files using the Lingvanex Translation API.

    This approach is especially useful for:

    • Command-line localization workflows;
    • CI/CD automation;
    • Server-side scripting;
    • Linux-based translation pipelines;
    • Quick JSON processing tasks.

    Before starting, install the jq utility, which simplifies JSON parsing and manipulation in Bash. The examples below use jq to extract and update translatable text values while preserving the original JSON structure.

    On Debian-based Linux distributions, you can install jq with the following commands:

    sudo apt update
    sudo apt install jq
    

    1. These lines set the source language, target language, the private translation server's URL, and the JSON file's path.

    SOURCE_LANGUAGE='en'  # Source language
    TARGET_LANGUAGE='fr'  # Target language
    PRIVATE_TRANSLATOR_URL='https://your-server-translator-url/api/translate'  # Translation server URL
    JSON_FILEPATH='/path-to-your-json-file'  # Path to the JSON file
    

    2. This function takes a text string as an argument and sends a POST request to the translation server. It uses curl to send the request and jq to parse the JSON response and extract the translated text. The function then echoes (returns) the translated text.

    translate() {
        local text="${1}"
        local translated_text="$(curl -s -X POST "${PRIVATE_TRANSLATOR_URL}" \
            -d "source=${SOURCE_LANGUAGE}" \
            -d "target=${TARGET_LANGUAGE}" \
            -d "q=${text}" | jq -r '.translatedText')"
        echo "${translated_text}"
    }
    

    3. This function is the main part of the script:

    1. It checks if the JSON file exists. If not, it prints an error message and exits.
    2. It reads the JSON file into a variable.
    3. It extracts all scalar (string) values from the JSON using jq, storing them in variable lines.
    4. It iterates over each extracted entry, translates each value, and replaces the original value with the translated value in the JSON.
    5. Finally, it prints the modified JSON.
    main() {
        local json_file_path="${1}"
        if [ ! -f "${json_file_path}" ]; then
            echo "File not found: ${json_file_path}"
            exit 1
        fi
        local json="$(cat "${json_file_path}")"
    
        local lines="$(echo "${json}" | jq -c 'paths(scalars) as $p | getpath($p) as $v | select($v | type == "string") | {path: $p, value: $v}')"
    
        while read entry; do
            key="$(echo "${entry}" | jq -rc '.path')"
            value="$(echo "${entry}" | jq -r '.value')"
            translated_value="$(translate "${value}")"
            json="$(echo "${json}" | jq --argjson key "${key}" --arg value "${translated_value}" 'setpath($key; $value)')"
        done <<< "${lines}"
    
        echo "${json}"
    }
    

    4. This line calls the main function with the path to the JSON file as an argument. It initiates the translation process for the JSON document.

    main '${JSON_FILEPATH}'
    

    Putting it to the Test: A Translation Example

    Now that we've covered the implementation in Python, JavaScript, and Bash, let's see how the JSON translation workflow works in a real-world scenario.

    In this example, we’ll translate a sample JSON dataset containing product information from English to French using the Lingvanex Translation API. The goal is to translate only the text-based values while preserving the original JSON structure, keys, nested objects, arrays, numeric values, and formatting.

    This example demonstrates how machine translation can be integrated into application localization, multilingual product catalogs, and automated JSON translation workflows without breaking compatibility with existing systems.

    Here is the source JSON data we’ll use for the translation process:

    {
    "products": [
        {
        "id": 1,
        "name": "Wireless Mouse",
        "description": "Ergonomic wireless mouse with adjustable DPI settings.",
        "price": 25.99,
        "category": "Electronics",
        "stock": 150,
        "reviews": [
            {
            "user": "JaneDoe",
            "rating": 4.5,
            "comment": "Great mouse, very responsive."
            },
            {
            "user": "JohnSmith",
            "rating": 4.0,
            "comment": "Good value for the price."
            }
        ]
        },
        {
        "id": 2,
        "name": "Mechanical Keyboard",
        "description": "RGB backlit mechanical keyboard with customizable keys.",
        "price": 79.99,
        "category": "Electronics",
        "stock": 85,
        "reviews": [
            {
            "user": "AliceW",
            "rating": 5.0,
            "comment": "Fantastic typing experience!"
            },
            {
            "user": "BobM",
            "rating": 4.2,
            "comment": "A bit noisy, but great quality."
            }
        ]
        }
    ]
    }
    

    We can feed this English JSON data into any of our code implementations (Python, JavaScript, or Bash). Each implementation uses the Lingvanex translation API to handle the language conversion.

    After running the code, here's the translated JSON output we obtained:

    {
    "products": [
        {
        "id": 1,
        "name": "Souris sans fil",
        "description": "Souris sans fil ergonomique avec paramètres DPI réglables.",
        "price": 25.99,
        "category": "Electronique",
        "stock": 150,
        "reviews": [
            {
            "user": "JaneDoe",
            "rating": 4.5,
            "comment": "Excellente souris, très réactive."
            },
            {
            "user": "JohnSmith",
            "rating": 4.0,
            "comment": "Bon rapport qualité-prix."
            }
        ]
        },
        {
        "id": 2,
        "name": "Clavier mécanique",
        "description": "Clavier mécanique rétroéclairé RVB avec touches personnalisables.",
        "price": 79.99,
        "category": "Electronique",
        "stock": 85,
        "reviews": [
            {
            "user": "AliceW",
            "rating": 5.0,
            "comment": "Expérience de frappe fantastique !"
            },
            {
            "user": "BobM",
            "rating": 4.2,
            "comment": "Un peu bruyant, mais de grande qualité."
            }
        ]
        }
    ]
    }
    

    Key Points to Verify in the Output

    After the translation process is complete, it is important to verify that the output JSON remains valid, accurate, and fully compatible with the original application or workflow.

    Pay special attention to the following aspects:

    • Structure preservation – the overall JSON hierarchy, nesting, arrays, and object relationships should remain unchanged after translation;
    • Targeted translation only – only text-based values such as product names, descriptions, labels, and user reviews should be translated. Keys, numbers, booleans, null values, placeholders, and other non-text elements should remain untouched;
    • Accurate language translation – the translated content should correctly reflect the meaning and context of the original text;
    • Placeholder and variable protection – dynamic values such as {{name}}, %s, {count}, or HTML fragments should remain unchanged to avoid breaking application logic or localization workflows;
    • Valid JSON formatting – the translated file should still pass JSON validation and be correctly parsed by applications, APIs, or frontend systems.

    By validating these elements across Python, JavaScript, and Bash implementations, developers can ensure that the JSON translation workflow is reliable, scalable, and suitable for real-world localization and automation environments.

    Important Considerations

    When translating JSON files automatically, it is important to ensure that the translation workflow remains reliable, secure, and compatible with your application or localization system.

    Keep the following best practices in mind:

    • Verify that your Lingvanex translation server URL is correct and accessible before starting the translation process;
    • Double-check source and target language codes to prevent incorrect translations;
    • Ensure that the JSON file path is valid and that the file can be accessed by the script;
    • Preserve JSON keys, placeholders, variables, and non-text data types during translation;
    • Validate the translated JSON output to confirm that the structure and formatting remain intact;
    • Be aware that larger JSON files or deeply nested structures may require additional processing time;
    • Consider batching translation requests or adding retry logic for large-scale localization workflows;
    • Use human review for critical content to improve translation accuracy, terminology consistency, and contextual quality.

    By following the workflow described in this guide, developers can automatically translate JSON files while preserving structure, formatting, and compatibility with existing systems. This approach is suitable for application localization, multilingual datasets, product catalogs, API responses, and other internationalization workflows.

    Lingvanex On-Premise Machine Translation provides a secure way to process JSON content within your own infrastructure, making it a practical solution for organizations that require privacy, customization, and full control over translation workflows.

    If you need assistance with deploying or integrating Lingvanex On-Premise Machine Translation into your localization workflow, the Lingvanex support team can help you configure and optimize your translation environment.

    Conclusion

    Translating JSON files requires more than simple text conversion. To maintain compatibility with applications, APIs, and localization systems, it is essential to preserve JSON structure, keys, nested objects, placeholders, and non-text data types throughout the translation process.

    In this guide, we demonstrated how to automatically translate JSON files using Lingvanex On-Premise Machine Translation with Python, JavaScript, and Bash. By translating only text-based values while preserving the original structure, developers can safely integrate machine translation into localization workflows, multilingual applications, datasets, and automation pipelines.

    With the Lingvanex Translation API, organizations can process JSON content securely within their own infrastructure while maintaining control over privacy, customization, and deployment environments.


    Frequently Asked Questions (FAQ)

    How do I translate a JSON file?

    To translate a JSON file, parse the file, extract text-based values, send them to a machine translation API, and rebuild the JSON with translated content. To preserve compatibility, translate only string values while keeping keys, numbers, arrays, booleans, and structure unchanged.

    Can JSON keys be translated?

    In most cases, JSON keys should not be translated because they are used internally by applications, APIs, and localization systems. Only user-facing text values should be translated, while keys remain unchanged.

    How to translate JSON while preserving structure?

    To preserve JSON structure during translation, translate only text-based values and keep keys, nesting, arrays, numbers, booleans, and null values unchanged. After translation, validate the JSON to ensure the file remains correctly formatted and usable.

    How to translate i18n JSON files automatically?

    i18n JSON files can be translated automatically by connecting a localization workflow to a machine translation API. During translation, placeholders, variables, keys, and formatting should remain unchanged to maintain application compatibility.

    How to validate translated JSON?

    Translated JSON can be validated using JSON linters, schema validation tools, or command-line utilities such as jq. Validation helps ensure the file remains correctly formatted and compatible with applications and APIs.

    How to translate nested JSON values?

    Nested JSON values can be translated with a recursive function that traverses objects and arrays, translates string values, and preserves all other data types and structure. This approach allows complex JSON files to be localized automatically.

    How to translate JSON without breaking placeholders?

    When translating JSON files, placeholders such as {{name}}, {count}, or %s should remain unchanged. Only the surrounding text values should be translated to avoid breaking application logic or localization workflows.

    Can machine translation break JSON formatting?

    Yes, machine translation can break JSON formatting if structural elements such as quotation marks, brackets, keys, or placeholders are modified. To prevent this, translate only text-based values while preserving the original JSON structure and formatting.

    Should JSON keys be localized?

    In most cases, JSON keys should not be localized because they are used internally by applications, APIs, and localization systems. Only user-facing text values should be translated, while keys remain unchanged.

    What parts of a JSON file should not be translated?

    JSON keys, numbers, boolean values, null values, IDs, URLs, placeholders, variables, and code fragments should usually remain unchanged during translation. Only user-visible text content should be translated.

    How to automate JSON localization workflows?

    JSON localization workflows can be automated by combining JSON parsing scripts with a machine translation API. This allows developers to extract translatable text, generate translated JSON files automatically, and integrate localization into CI/CD pipelines or application workflows.

    Can translated JSON files be validated automatically?

    Yes, translated JSON files can be validated automatically using JSON linters, schema validation tools, or command-line utilities such as jq. Validation helps ensure that the translated JSON remains properly formatted and compatible with applications and APIs.

    More fascinating reads await

    On-premise vs. Cloud (2026): Key Differences, Architecture, and Trade-Offs

    On-premise vs. Cloud (2026): Key Differences, Architecture, and Trade-Offs

    March 10, 2026

    Offline Translation Without Internet (2026): Guide for Businesses and Developers

    Offline Translation Without Internet (2026): Guide for Businesses and Developers

    March 5, 2026

    Translation API Comparison: Lingvanex, Google, DeepL – Pricing, Security, On-Prem

    Translation API Comparison: Lingvanex, Google, DeepL – Pricing, Security, On-Prem

    March 3, 2026

    ×