Tutorial: Translating JSON Dictionary Values using Python and Google Translate
In this tutorial, we’re going to learn how to translate values in a JSON dictionary from English to Spanish using Python and the googletrans
library, a free and unlimited python library that implemented Google Translate API.
Requirements
To complete this tutorial, you’ll need the following:
- Python 3 installed on your system.
- Access to a Jupyter Notebook, Google Colab, or a Python script file.
- Internet access, as we’ll be using the online Google Translate service.
Step 1: Install googletrans
Library
The first step is to install the googletrans
library. You can do this with pip:
!pip install googletrans==3.1.0a0
Step 2: Import Required Libraries
Next, we’ll import the necessary libraries. We’ll need the json
library to work with JSON data, the googletrans
library to translate text, and the re
library to identify placeholders in our text:
import json
import re
from googletrans import Translator
Step 3: Initialize the Translator
We will then initialize our Translator
object from googletrans
:
translator = Translator()
Step 4: Create Our Translation Function
Next, we create a function that will take an English JSON dictionary and return a Spanish JSON dictionary. Our function will iterate through each key-value pair in the English dictionary, translate the value to Spanish, and store it in the Spanish dictionary with the same key:
def translate_dict(en_dict):
es_dict = {}
for key, value in en_dict.items():
# Identify placeholders
placeholders = re.findall(r'{.*?}', value)
# Remove placeholders from the original string
for placeholder in placeholders:
value = value.replace(placeholder, '')
# Translate the string without placeholders
translation = translator.translate(value, dest='es')
# Add the placeholders back to the translated string
translated_value = translation.text
for placeholder in placeholders:
translated_value += ' ' + placeholder
es_dict[key] = translated_value.strip()
return es_dict
In this function, we first identify placeholders (text within {}). We then remove the placeholders from the original string, translate the rest of the string, and then add the placeholders back to the translated string.
Step 5: Use the Function
Finally, we can use our function to translate an English JSON dictionary:
en_dict = {
"000a1a966f5e5aba0e7c": "Update Settings",
"00a60ec8ca21b351da90": "Terms Url",
#...
# include all the keys and values you want to translate
#...
}
# Get the Spanish translation
es_dict = translate_dict(en_dict)
# Print the Spanish dictionary
print(json.dumps(es_dict, ensure_ascii=False))
Conclusion
Congratulations! You’ve just created a Python script to translate the values in a JSON dictionary using Google Translate. This can be extremely useful in applications such as internationalizing a web application, translating user content, and much more. Happy coding!