Skip to content

Commit 425f693

Browse files
#12 - python
1 parent 8c221e2 commit 425f693

File tree

1 file changed

+178
-0
lines changed

1 file changed

+178
-0
lines changed
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
#12 { Retos para Programadores } JSON Y XML
2+
3+
'''
4+
* IMPORTANTE: Sólo debes subir el fichero de código como parte del ejercicio.
5+
*
6+
* EJERCICIO:
7+
* Desarrolla un programa capaz de crear un archivo XML y JSON que guarde los
8+
* siguientes datos (haciendo uso de la sintaxis correcta en cada caso):
9+
* - Nombre
10+
* - Edad
11+
* - Fecha de nacimiento
12+
* - Listado de lenguajes de programación
13+
* Muestra el contenido de los archivos.
14+
* Borra los archivos.
15+
*
16+
* DIFICULTAD EXTRA (opcional):
17+
* Utilizando la lógica de creación de los archivos anteriores, crea un
18+
* programa capaz de leer y transformar en una misma clase custom de tu
19+
* lenguaje los datos almacenados en el XML y el JSON.
20+
* Borra los archivos.
21+
22+
'''
23+
24+
# Bibliography reference
25+
# Professional JavaScript for web developers by Matt Frisbie [Frisbie, Matt] (z-lib.org)
26+
#Python Notes for Professionals. 800+ pages of professional hints and tricks (GoalKicker.com) (Z-Library)
27+
# GPT
28+
29+
# JSON
30+
# JSON stands for "JavaScript Object Notation", but it's not JavaScript.
31+
# Think of it as just a data serialization format that happens to be directly usable as a JavaScript literal.
32+
# However, it is not advisable to directly run (i.e. through eval()) JSON that is fetched from an external source.
33+
# Functionally, JSON isn't very different from XML or YAML – some confusion can be avoided if JSON is just imagined as some serialization format that looks very much like JavaScript.
34+
35+
import json
36+
import os
37+
import xml.etree.ElementTree as ET
38+
from xml.dom import minidom
39+
from datetime import datetime
40+
41+
# Short for print
42+
log = print
43+
44+
# JSON string example
45+
json_string = '[{"name":"Kox","age":51},{"name":"Fanny","age":17}]'
46+
data = json.loads(json_string, object_hook=lambda d: {k: v.upper() if k == 'name' else v for k, v in d.items()})
47+
log(data) # [{'name': 'KOX', 'age': 51}, {'name': 'FANNY', 'age': 17}]
48+
49+
# Parsing with a reviver function for date
50+
json_string2 = '{"date":"2024-10-12T12:28:40.143Z"}'
51+
data2 = json.loads(json_string2, object_hook=lambda d: {k: (datetime.fromisoformat(v[:-1]) if k == 'date' else v) for k, v in d.items()})
52+
log(data2) # {'date': datetime.datetime(2024, 10, 12, 12, 28, 40, 143000)}
53+
54+
# JSON.stringify equivalent in Python
55+
log(json.dumps(True)) # 'true'
56+
log(json.dumps(154)) # '154'
57+
log(json.dumps('roadmap')) # '"roadmap"'
58+
log(json.dumps({})) # '{}'
59+
log(json.dumps({'name': 'Any'})) # '{"name": "Any"}'
60+
log(json.dumps([41, True, 'System Engineering'])) # '[41, true, "System Engineering"]'
61+
log(json.dumps({"x": 4, "y": 4}, indent=2)) # Pretty print with indentation:
62+
'''
63+
{
64+
"x": 4,
65+
"y": 4
66+
}
67+
68+
'''
69+
70+
# Data to save
71+
data1 = {
72+
"name": "Niko Zen",
73+
"age": 30,
74+
"birthDate": "1983-08-08",
75+
"languages": ["JavaScript", "Python", "Ruby", "Rust", "Bash"]
76+
}
77+
78+
# Function to create a JSON file
79+
def create_json(data):
80+
json_data = json.dumps(data, indent=2)
81+
with open('data.json', 'w') as json_file:
82+
json_file.write(json_data)
83+
log("Content of the JSON file:") # Content of the JSON file:
84+
log(json_data)
85+
86+
'''
87+
{
88+
"name": "Niko Zen",
89+
"age": 30,
90+
"birthDate": "1983-08-08",
91+
"languages": [
92+
"JavaScript",
93+
"Python",
94+
"Ruby",
95+
"Rust",
96+
"Bash"
97+
]
98+
}
99+
100+
'''
101+
102+
# Function to create an XML file
103+
def create_xml(data):
104+
person = ET.Element("person")
105+
ET.SubElement(person, "name").text = data["name"]
106+
ET.SubElement(person, "age").text = str(data["age"])
107+
ET.SubElement(person, "birthDate").text = data["birthDate"]
108+
languages = ET.SubElement(person, "languages")
109+
for lang in data["languages"]:
110+
ET.SubElement(languages, "language").text = lang
111+
112+
# Convert the ElementTree to a string
113+
xml_data = ET.tostring(person, encoding='unicode')
114+
115+
# Use minidom to pretty-print the XML
116+
pretty_xml = minidom.parseString(xml_data).toprettyxml(indent=" ")
117+
118+
# Write the pretty-printed XML to a file
119+
with open('data.xml', 'w') as xml_file:
120+
xml_file.write(pretty_xml)
121+
122+
log("Content of the XML file:") # Content of the XML file:
123+
log(pretty_xml)
124+
'''
125+
<?xml version="1.0" ?>
126+
<person>
127+
<name>Niko Zen</name>
128+
<age>30</age>
129+
<birthDate>1983-08-08</birthDate>
130+
<languages>
131+
<language>JavaScript</language>
132+
<language>Python</language>
133+
<language>Ruby</language>
134+
<language>Rust</language>
135+
<language>Bash</language>
136+
</languages>
137+
</person>
138+
'''
139+
140+
# Function to delete files
141+
def delete_files():
142+
os.remove('data.json')
143+
os.remove('data.xml')
144+
log("Files deleted.")
145+
146+
# Custom class
147+
class Person:
148+
def __init__(self, name, age, birth_date, languages):
149+
self.name = name
150+
self.age = age
151+
self.birth_date = birth_date
152+
self.languages = languages
153+
154+
# Function to read and transform data
155+
def read_and_transform():
156+
with open('data.json', 'r') as json_file:
157+
json_data = json.load(json_file)
158+
159+
with open('data.xml', 'r') as xml_file:
160+
xml_data = xml_file.read()
161+
162+
# Transform XML to object
163+
xml_doc = ET.fromstring(xml_data)
164+
name = xml_doc.find("name").text
165+
age = int(xml_doc.find("age").text)
166+
birth_date = xml_doc.find("birthDate").text
167+
languages = [lang.text for lang in xml_doc.find("languages").findall("language")]
168+
169+
# Create an instance of Person
170+
person = Person(name, age, birth_date, languages)
171+
log("Data transformed to Person class:") # Data transformed to Person class:
172+
log(person.__dict__) # {'name': 'Niko Zen', 'age': 30, 'birth_date': '1983-08-08', 'languages': ['JavaScript', 'Python', 'Ruby', 'Rust', 'Bash']}
173+
174+
if __name__ == "__main__":
175+
create_json(data1)
176+
create_xml(data1)
177+
read_and_transform()
178+
delete_files() #Files deleted.

0 commit comments

Comments
 (0)