|
| 1 | +# ╔═════════════════════════════════════╗ |
| 2 | +# ║ Autor: Kenys Alvarado ║ |
| 3 | +# ║ GitHub: https://github.com/Kenysdev ║ |
| 4 | +# ║ 2024 - Python ║ |
| 5 | +# ╚═════════════════════════════════════╝ |
| 6 | + |
| 7 | +# ----------------------------------- |
| 8 | +# * JSON Y XML |
| 9 | +# ----------------------------------- |
| 10 | +# - son formatos de intercambio de datos que estructuran información. |
| 11 | +# - JSON (JavaScript Object Notation) y XML (eXtensible Markup Language) |
| 12 | + |
| 13 | +import os |
| 14 | +import ast |
| 15 | +import json |
| 16 | +import xml.dom.minidom |
| 17 | + |
| 18 | +#____________________________________ |
| 19 | +# * JSON |
| 20 | +dict_user = { |
| 21 | + "name": "Ken", |
| 22 | + "age": 121, |
| 23 | + "dob": "1903-03-19", |
| 24 | + "prog_langs": ["cs", "py", "vb", "rs", "js"] |
| 25 | +} |
| 26 | + |
| 27 | +# _______________ |
| 28 | +# Serialización: el proceso de convertir un objeto a una |
| 29 | +# cadena de caracteres en formato JSON. |
| 30 | +json_user = json.dumps(dict_user) |
| 31 | +# {"name": "Ken", "age": 121, "dob": "1903-03-19", ....} |
| 32 | + |
| 33 | +# Con indentación. |
| 34 | +json_user = json.dumps(dict_user, indent=4) |
| 35 | + |
| 36 | +# Crear fichero |
| 37 | +with open("user.json", 'w') as file: |
| 38 | + json.dump(dict_user, file, indent=4) |
| 39 | + |
| 40 | +# _______________ |
| 41 | +# Deserialización: convertir una cadena de caracteres JSON a un objeto. |
| 42 | +with open("user.json", 'r') as file: |
| 43 | + data = json.load(file) |
| 44 | +print("Objeto cargado\n", data, "\n") |
| 45 | + |
| 46 | +format_json = json.dumps(data, indent=4) |
| 47 | +print("Objeto a formato json\n",format_json, "\n") |
| 48 | + |
| 49 | +#____________________________________ |
| 50 | +# * XML |
| 51 | + |
| 52 | +# Serialización |
| 53 | +doc = xml.dom.minidom.Document() |
| 54 | +root = doc.createElement("user") |
| 55 | +doc.appendChild(root) |
| 56 | + |
| 57 | +for key, value in dict_user.items(): |
| 58 | + elem = doc.createElement(key) |
| 59 | + text = doc.createTextNode(str(value)) |
| 60 | + elem.appendChild(text) |
| 61 | + root.appendChild(elem) |
| 62 | + |
| 63 | +# Guardar |
| 64 | +with open("user.xml", "w") as f: |
| 65 | + f.write(doc.toprettyxml()) |
| 66 | + |
| 67 | +# _______________ |
| 68 | +# cargar |
| 69 | +with open("user.xml", "r") as f: |
| 70 | + xml_content = f.read() |
| 71 | + print("Cargar documento\n", xml_content, "\n") |
| 72 | + |
| 73 | +# cargar un elemento especifico. |
| 74 | +doc = xml.dom.minidom.parse("user.xml") |
| 75 | +age_value = doc.getElementsByTagName("age")[0] |
| 76 | +age = age_value.firstChild.data |
| 77 | +print("Edad: ", age) |
| 78 | + |
| 79 | +#____________________________________ |
| 80 | +# EJERCICIO |
| 81 | +""" |
| 82 | + * Utilizando la lógica de creación de los archivos anteriores, crea un |
| 83 | + * programa capaz de leer y transformar en una misma clase custom de tu |
| 84 | + * lenguaje los datos almacenados en el XML y el JSON. |
| 85 | + * Borra los archivos. |
| 86 | +""" |
| 87 | + |
| 88 | +class Xml_or_json: |
| 89 | + def __init__(self, path): |
| 90 | + file_name, file_extension = os.path.splitext(path) |
| 91 | + self.path = path |
| 92 | + self.extension = file_extension.lower() |
| 93 | + self.dic_user = {} |
| 94 | + |
| 95 | + def as_dict(self) -> list: |
| 96 | + try: |
| 97 | + if self.extension == ".json": |
| 98 | + with open(self.path, 'r') as file: |
| 99 | + self.dic_user = json.load(file) |
| 100 | + print("Archivo .json cargado") |
| 101 | + return self.dic_user |
| 102 | + |
| 103 | + elif self.extension == ".xml": |
| 104 | + def _get_value(key: str) -> str: |
| 105 | + doc = xml.dom.minidom.parse(self.path) |
| 106 | + value = doc.getElementsByTagName(key)[0] |
| 107 | + value_str = value.firstChild.data |
| 108 | + return value_str |
| 109 | + |
| 110 | + self.dic_user["name"] = _get_value("name") |
| 111 | + self.dic_user["age"] = int(_get_value("age")) |
| 112 | + self.dic_user["dob"] = _get_value("dob") |
| 113 | + self.dic_user["prog_langs"] = ast.literal_eval(_get_value("prog_langs")) |
| 114 | + |
| 115 | + print("Archivo .xml cargado") |
| 116 | + return self.dic_user |
| 117 | + |
| 118 | + else: |
| 119 | + print("Archivo no compatible.") |
| 120 | + |
| 121 | + except Exception as ex: |
| 122 | + print("Error -> ", ex) |
| 123 | + |
| 124 | +print("\nEJERCICIO\n") |
| 125 | +#__________ |
| 126 | +file = Xml_or_json("user.json") |
| 127 | +dic_user: dict = file.as_dict() |
| 128 | +print(dic_user) |
| 129 | +#__________ |
| 130 | +file = Xml_or_json("user.xml") |
| 131 | +dic_user: dict = file.as_dict() |
| 132 | +print(dic_user) |
| 133 | + |
| 134 | +# eliminar |
| 135 | +os.remove("user.xml") |
| 136 | +os.remove("user.json") |
0 commit comments