json (JavaScript Object Notation) est le format texte le plus utilisé pour échanger des données structurées (entre APIs, fichiers de config, etc.). Le module standard json fait la conversion entre json et structures Python.
Correspondance json ↔ Python :
JSON object { "k": v } ↔ dict
JSON array [1, 2, 3] ↔ list
JSON string "hello" ↔ str
JSON number 42 ou 3.14 ↔ int ou float
JSON true/false ↔ True / False
JSON null ↔ Nonejson.loads(texte) → parse une str JSON → objet Python
json.load(fichier) → parse un fichier ouvert
json.dumps(obj) → sérialise un objet Python → str JSON
json.dump(obj, f) → écrit directement dans un fichier(Mnemonic : le "s" à la fin = string)
import jsontexte = '{"nom": "Alice", "age": 28, "skills": ["Python", "SQL"]}'
data = json.loads(texte)print(data['nom']) # Alice
print(data['skills']) # ['Python', 'SQL']
print(data['skills'][0]) # PythonUne fois parsé, data est un dict Python normal : on accède par clé.
personne = {'nom': 'Alice', 'age': 28}
json.dumps(personne) # '{"nom": "Alice", "age": 28}'
json.dumps(personne, indent=2) # joliment formaté
json.dumps(personne, ensure_ascii=False) # garde les accents au lieu de \uXXXXLes clés json sont toujours des str. Si tu as un dict avec des clés int, json.dumps les convertira en str automatiquement.
Pour lire un fichier .json :
with open('config.json') as f:
config = json.load(f)
Envie d'aller plus loin ? Découvrez nos formations certifiées Bac+2 à Bac+5 →