Learn how to retrieve values from a .json file in real-time and then perform comparisons with user input using Python

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

Answer №1

After successfully fixing the json you provided, here is a modified code snippet that should help solve your issue.

This code reads data from the countries.json file and retrieves the official country name along with translations in various languages:

import json

with open('countries.json') as f:
    countries = json.load(f)

official_keys = {}
for country in countries:
    official_keys[country['name']['official']] = country['translations']

input_code = input('Enter country code: ')
for name, keys  in official_keys.items():
    if input_code in keys:
        print(name, '=>', keys[input_code]["official"])

Example interaction:

Enter country code: fra
Canada => Canada
German Democratic Republic => Deutsche Demokratische Republik

Answer №2

To efficiently manage country codes, storing them in a dictionary format is recommended. This allows for easy access to the data. It's important to note that this method works best when each country has a unique code. When opening a file, it's good practice to use the 'with' statement in Python to ensure automatic closure of the file and prevent any potential data corruption.

    with open('./countries.json', 'r') as f:
        translationKeys = json.load(f)[0]["translations"]

Now you can compare user input against the stored country codes:

    inp = input('Please enter a country code:')
    if inp in translationKeys.keys():
        print(translationKeys[inp]["official"])
    else:
        print('This country code was not found')

If you wish to display all country codes, you can iterate through the JSON file by utilizing dict.get() which will return the corresponding key if found, or None:

    inp = input()
    for element in translationKeys:
        if element == inp:
            print(translationKeys[inp]['official'])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to prevent the imported JQuery from causing issues with current code implementations?

Being a novice developer in Html/Javascript/CSS/Jquery coding, I recently encountered an issue while integrating Jquery into my project. When I imported Jquery, the styling of simple buttons went haywire. Jquery worked perfectly fine when using its classes ...

The express js backend (mongodb) is returning {error:{ }}

I'm learning how to POST Data to a Mongo DB using Express.js. Recently, I picked up Express.js for backend server development and this is my app.js const express = require("express"); const mongoose = require("mongoose"); require("dotenv/config") con ...

Oops! Next JS encountered an unhandled runtime error while trying to render the route. The

I keep receiving the error message Unhandled Runtime Error Error: Cancel rendering route Within my navBar, I have implemented the following function: const userData={ id:1, email: "", name: "", lastName: "", ...

Guidelines for incorporating my company's PPT slide designs in your python-pptx presentation

When I run the following code: from pptx import Presentation prs = Presentation() slide_layout = prs.slide_layouts[0] prs.save("Final.pptx") A PowerPoint presentation is generated with a single slide that uses the default title layout. However, when I o ...

What are some ways to manipulate and work with extensive JSON data using pandas?

I am currently working with a 200mb txt file that contains approximately 25k JSON files, consisting of metadata and content from newspaper articles. My goal is to reduce the size of the file by keeping only the relevant data for my analysis, specifically t ...

GoLang Struct JSON conversion issue

I have a struct called "Sim" that I need to convert into JSON after populating it with data. When I print the variable s, it displays the correct information, but when I print data, it appears blank. Can someone help me figure out how to properly convert ...

Guide on how to transmit an error message from PHP when handling a jQuery Ajax post request

Greetings! This is my inaugural inquiry, so please understand if I am a bit apprehensive. I am facing an issue in the following scenario... I have an Ajax request structured like this: $.ajax({ url: "test.php", method: "POST", data: { ...

The validation function for email addresses in Express-validator seems to be malfunctioning

I've encountered an issue with the validation process in my code. Everything seems to be working fine except for the .isEmail method, which keeps flagging even valid email addresses as invalid. No matter how I adjust the validation rules, the problem ...

npm causing problems with babel-cli

While working on building a section of my library with Babel, I've encountered some issues when running Babel commands through npm. In my npm script named "build," the following commands are executed: { "prebuild": "rm -rf && mkdir dist", ...

Encountering a Broken Pipe Error when using Selenium in conjunction with the ChromeDriver

While attempting to scrape a website's index page and locate an element containing login text, I ran the following code: from selenium import webdriver import os chromedriver = "/usr/bin/chromedriver" os.environ["webdriver.chrome.driver"] = chromedr ...

What is the process for dynamically altering the source file of VueRouter?

Hello, I am working on a project that involves multiple roles using VueJs and Laravel. Laravel is used as the back-end while Vuejs serves as the front-end. The project has three different roles: User, Modirator, and Editor. Here is a snippet of my code ...

Simulating a service call in an AngularJS controller

Here is the code for my Controller: (function () { 'use strict'; angular.module('myApp').controller('myCtrl', function ($scope, myService) { // Start -----> Service call: Get Initial Data myService ...

The video is not displaying on the webpage when connected locally, but it appears when the source is a URL

Recently, while practicing some basic tasks on a cloud IDE called Goorm, I encountered an issue with displaying a video on a simple webpage. The EJS file and the video were located in the same folder, but when I set the src attribute of the video tag to "m ...

Getting a file in php: a step-by-step guide

My PHP function is meant for downloading an encrypted file after processing the data The Connect Class is used for database connection class License extends Connect { function __construct() { parent::__construct(); } public func ...

Using AngularJS to Retrieve a Specific DOM Element Using its Unique Identifier

Example Please take a look at this Plunkr example. Requirement I am looking for a way to retrieve an element by its id. The provided code should be capable of applying a CSS class to any existing DOM element within the current view. This functionality ...

I'm currently struggling to utilize liquid to remove certain characters from product tags in order to optimize them for search engine visibility

When it comes to filtering, I utilize tags with a low-dash before each word. However, some of these tags have special search keywords that aren't producing results because the user's search input doesn't include the character. In an attempt ...

Leveraging global variables within Vuex state management strategy

I have successfully added custom global variables into Vue by injecting them. Here is the code snippet: export default function (props, inject) { inject('models', { register(name) { const model = require(`@/models/${name}. ...

Changing month names from numerical format to text in pandas

Below is the dataframe that I am currently working with: High Low Open Close Volume Adj Close year pct_day month day 1 1 NaN NaN NaN NaN NaN NaN 2010.0 0.000000 2 7869.853149 7718.482498 7779.655014 7818 ...

Add more functionality to the server.js script

I have the server.js file, which serves as the entry point for my Node application and is responsible for invoking three different functions (these functions are only called once when the server is up, such as creating child processes, validation, etc), wh ...

req.body is not defined or contains no data

I am facing an issue with my controllers and routers. bookController.js is functioning perfectly, but when I try to use userControllers for registration and login logic, req.body always appears empty. I tried logging the form data using console.log, but it ...