-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson2md.py
More file actions
67 lines (53 loc) · 2.21 KB
/
json2md.py
File metadata and controls
67 lines (53 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python3
# ───────────────────────────────────────────────────────────────
# Obtener un listado de estudiantes en formato .md (markdown)
# a partir del json obtenido de aula virtual
# ───────────────────────────────────────────────────────────────
import sys
import json
# ─── Nombre fichero JSON a leer
JSON_FILE = "listado-estudiantes.json"
# ─── Nombre fichero (markdown) a generar
MD_FILE = "listado-estudiantes.md"
# ─── Campos de acceso a los estudiantes
NOMBRE = 'nombre'
APELLIDOS = 'apellidos'
# ───────────
# MAIN
# ───────────
print()
# ──── Abrir fichero json
try:
with open(JSON_FILE, "r", encoding="utf8") as fich_json:
datos = json.load(fich_json)
except FileNotFoundError:
print(f"❌ ERROR! Fichero NO encontrado: {JSON_FILE}\n")
sys.exit(1)
except json.JSONDecodeError:
print("❌ ERROR! Fichero JSON NO VALIDO\n")
sys.exit(1)
except Exception as e:
print(f"❌ ERROR! Desconocido: {e}\n")
sys.exit(1)
# ──── Comprobaciones del fichero
print(f"✅ Fichero JSON abierto: {JSON_FILE}")
# ────── El objeto principal es una lista de listas
# ── Comprobar que existe la primera lista
if not isinstance(datos, list):
print("❌: Error en json. Se espera una lista []\n")
sys.exit(1)
# ── Consumir la primera lista
# ── Lo que nos queda es un listado de estudiantes
listado = datos[0]
# ── Generar listado en markdown en fichero de salida
# ── TODO: 🚧 Gestionar errores
with open(MD_FILE, "w", encoding="utf8") as fich_md:
# ── Recorrer todos los estudiantes
for i, student in enumerate(listado, start=1):
# ── Texto a imprimir por cada estudiante
entry = f"# {i}) {student[NOMBRE]} {student[APELLIDOS]}\n\n"
# ── Escribir en el fichero
fich_md.write(entry)
# ──── Fin. Notificar la escritura del fichero
print(f"✅ Listado generado: {MD_FILE}")
print()