python
import json
daten = {'name': 'Anna', 'tags': ['a', 'b'], 'aktiv': True, 'chef': None}
text = json.dumps(daten, indent=2, ensure_ascii=False) # Python zu JSON-Text
zurueck = json.loads(text) # JSON-Text zu Python
with open('daten.json', 'w', encoding='utf-8') as f:
json.dump(daten, f, indent=2, ensure_ascii=False) # direkt in Datei
with open('daten.json', encoding='utf-8') as f:
geladen = json.load(f) # direkt aus Datei
| Funktion | Parameter |
|---|---|
dumps(obj, indent=None, ensure_ascii=True, sort_keys=False) |
indent: Einrückung für schöne Ausgabe. ensure_ascii=False erhält Umlaute. sort_keys=True sortiert die Schlüssel |
loads(text) |
JSON-String zu Python |
dump(obj, datei, ...), load(datei) |
wie oben, aber mit Dateiobjekt |
Die Abbildung: JSON-Objekt wird dict, Array wird list, true/false werden True/False, null wird None.