ConsigneParse la chaîne JSON `'{"nom": "Alice", "age": 28, "skills": ["Python", "SQL"]}'` et affiche le nom et les skills
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 } ↔ dictJSON array [1, 2, 3] ↔ listJSON string "hello" ↔ strJSON number 42 ou 3.14 ↔ int ou floatJSON true/false ↔ True / FalseJSON null ↔ Nonejson.loads(texte) → parse une str JSON → objet Pythonjson.load(fichier) → parse un fichier ouvertjson.dumps(obj) → sérialise un objet Python → str JSONjson.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']) # Aliceprint(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 →