Semaine 4, jour 2

This commit is contained in:
gauvainboiche
2026-01-14 10:21:12 +01:00
parent aad907f110
commit 4911bbd40c
32 changed files with 912 additions and 1 deletions

54
Semaine_04/Jour_03.md Normal file
View File

@@ -0,0 +1,54 @@
## Sérialisation, Dé-sérialisation
Sérialisation => On prend des objets, on transforme en JSON
Dé-sérialisation => On prend un JSON, on transforme en objets
### Exemple de sérialisation
On prend une liste classique
```py
livres = [{"titre": "1984", "auteur": "Orwell"}, {"titre": "LSDA", "auteur": "Tolkien"}]
```
On peut donc traiter un fichier JSON avec la fonction `open` et le sérialiser avec `dump` :
```py
import json
livres = [{"titre": "1984", "auteur": "Orwell"}, {"titre": "LSDA", "auteur": "Tolkien"}]
# file=/path/ , w-rite
fichier_json = open("livres.json", "w")
json.dump(livres, fichier_json)
fichier_json.close()
```
Ou, avec un `Context-Manager` au lieu d'ouvrir et de fermer :
```py
import json
livres = [{"titre": "1984", "auteur": "Orwell"}, {"titre": "LSDA", "auteur": "Tolkien"}]
with open("livres.json", "w") as fichier_json:
json.dump(livres, fichier_json, indent= 4)
```
### Exemple de dé-sérialisation
```py
import json
livres = [{"titre": "1984", "auteur": "Orwell"}, {"titre": "LSDA", "auteur": "Tolkien"}]
with open("livres.json", "w") as fichier_json:
objet = json.load(fichier_json)
print(objet)
objet.append({"titre": "Alice aux pays", "auteur": "Caroll"})
with open("livres.json", "w") as fichier_json:
json.dump(objet, fichier_json, indent= 4)
```