## 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) ```