Ci-dessous, les différences entre deux révisions de la page.
Prochaine révision | Révision précédente | ||
python:json [2020/12/13 08:32] marclebrun créée |
python:json [2021/10/20 08:25] (Version actuelle) marclebrun [Encodage] |
||
---|---|---|---|
Ligne 1: | Ligne 1: | ||
====== JSON ====== | ====== JSON ====== | ||
- | Doc: [[https://docs.python.org/fr/3/library/json.html]] | + | * [[https://docs.python.org/fr/3/library/json.html]] |
+ | * [[https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/|Reading and Writing JSON to a File in Python]] | ||
+ | |||
+ | | data = **json.load**(f, ...) | Décodage depuis un fichier | | ||
+ | | data = **json.loads**(s, ...) | Décodage depuis une chaîne | | ||
+ | | **json.dump**(f, data, ...) | Encodage vers un fichier | | ||
+ | | **json.dumps**(data, ...) | Encodage vers une chaîne | | ||
+ | |||
+ | |||
+ | ===== Encodage ===== | ||
+ | |||
+ | <code python> | ||
+ | import json | ||
+ | |||
+ | data = [ | ||
+ | 'foo', | ||
+ | { | ||
+ | 'bar': ('baz', None, 1.0, 2) | ||
+ | } | ||
+ | ] | ||
+ | |||
+ | j = json.dumps(data) | ||
+ | </code> | ||
+ | |||
+ | Avec indentation : | ||
+ | |||
+ | <code python> | ||
+ | j = json.dumps(data, indent=4) | ||
+ | print(j) | ||
+ | </code> | ||
+ | |||
+ | Vers un fichier : | ||
+ | |||
+ | <code python> | ||
+ | with open('data.txt', 'w') as f: | ||
+ | json.dump(data, f, indent=4) | ||
+ | </code> | ||
+ | |||
+ | ===== Décodage ===== | ||
+ | |||
+ | Depuis une chaîne : | ||
+ | |||
+ | <code python> | ||
+ | import json | ||
+ | |||
+ | data = json.loads(str) | ||
+ | </code> | ||
+ | |||
+ | Depuis un fichier : | ||
<code python> | <code python> | ||
import json | import json | ||
+ | with open("/home/marc/fichier.json", 'r') as f: | ||
+ | data = json.load(f) | ||
</code> | </code> | ||