Why create a JavaScript object using Python? To do it in an automated way๐
If we have to manage information modeled through JavaScript objects, we could run into the problem of not adequately updating all the data that the object needs. This certainly involves having incorrect data but also investing resources in reviewing our application.
We could then create a script in Python that helps us update all the data that populates the JavaScript object and save it in a file that allows us to do a quick copy & paste.
๐ Do you like Techelopment? Check out the site for all the details!
Creating the Python Script
We will build a JavaScript object to store employee data as shown below:
{
name: "Tom",
surname: "Smith",
dob: "10/21/1977",
job: {
title: "Software Engineer",
role: "Project Manager",
department: "Technology&Development",
}
}
Our Python script will ask the user for the following data:
- Name
- Surname
- Date of birth
- Job title
- Job role
- Job department
Once the script gets this data from the user, it will build and save the JavaScript object in the javascript_object-<name>_<surname>.txt
file.
def main():
print("Employee object data:\n")
# Ask data to the user
name = input("- Name: ")
surname = input("- Surname: ")
dob = input("- DOB (mm/dd/yyyy): ")
job_title = input("- Job title: ")
job_role = input("- Job role: ")
job_department = input("- Job department: ")
# Create the JavaScript object
employee_data = f"""
{{
name: "{name}",
surname: "{surname}",
dob: "{dob}",
job: {{
title: "{job_title}",
role: "{job_role}",
department: "{job_department}",
}}
}}
"""
print("\nJavaScript object saving...")
file_name = f"javascript_object-{name}_{surname}.txt"
# Save JavaScript object structure in a file
with open(file_name, "w") as js_file:
js_file.write(employee_data)
print(f"JavaScript object successfully saved in {file_name}")
# Run script
if __name__ == "__main__":
main()
other_js = input("\nDo you wanna make another JavaScript object [y/n]")
while other_js == "y":
main()
other_js = input("\nDo you wanna make another JavaScript object [y/n]")
print("bye bye :)")
input("Hit Enter to exit")
Running the script
Here is an example of running the script to generate the JavaScript object shown above:
Employee object data:
- Name: Tom
- Surname: Smith
- DOB (mm/dd/yyyy): 10/21/1977
- Job title: Software Engineer
- Job role: Project Manager
- Job department: Technology&Development
JavaScript object saving...
JavaScript object successfully saved in javascript_object-Tom_Smith.txt
Do you wanna make another JavaScript object [y/n]n
bye bye :)
Hit Enter to exit
Follow me #techelopment
Official site: www.techelopment.it
Medium: @techelopment
Dev.to: Techelopment
facebook: Techelopment
instagram: @techelopment
X: techelopment
telegram: @techelopment_channel
youtube: @techelopment
whatsapp: Techelopment
Top comments (0)