I have a JSON file structured like this:
[
{
"name": {
"common": "Aruba",
"official": "Aruba",
"native": {
"nld": {
"official": "Aruba",
"common": "Aruba"
},
"pap": {
"official": "Aruba",
"common": "Aruba"
}
}
},
"tld": [
".aw"
],
...
}]
Using JavaScript, I access this data with the code
const data = require('./countries.json');
. My goal is to extract the translation keys
, such as ces
, deu
, etc., dynamically and store them in an array called keys
. Then based on user input, if it matches one of the keys
, the program should print the official name of all countries using that key.
In my JavaScript, I use the following methods to achieve this:
// JavaScript Code
const data = require('./countries.json');
const keys = [];
data.forEach((element) => {
Object.keys(element.translations).forEach((item) => {
keys.push(item);
}) ;
});
/**
*Removes all duplicate translation keys
*@param {1} keys of translation keys
*@return {unique} a unique array of translation keys
*/
function removeDuplicates (keys) {
const unique = [];
keys.forEach((element) => {
if (!unique.includes(element)) {
unique.push(element);
}
});
return unique;
}
...
To achieve the same functionality in Python, you can use the following code snippet:
# Python Code
import json
with open('./countries.json') as f:
translationKeys = json.load(f)
keys = []
for i in translationKeys[0]["translations"]:
keys.append(i)
print(keys)
This Python code will retrieve and store the keys similar to the JavaScript implementation. You can then enhance it to print the values based on user input, just like how it's done in the JavaScript version.
If you need more context or want to explore the full project, you can check out the GitHub link: https://github.com/TheRadioDept/technical-question