Semaine 4, jour 2
This commit is contained in:
54
Semaine_04/Jour_03.md
Normal file
54
Semaine_04/Jour_03.md
Normal 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)
|
||||
```
|
||||
Reference in New Issue
Block a user