« JSON en Python » : différence entre les versions
(parsing) |
mAucun résumé des modifications |
||
| (2 versions intermédiaires par le même utilisateur non affichées) | |||
| Ligne 39 : | Ligne 39 : | ||
</syntaxhighlight> | </syntaxhighlight> | ||
== Importer du JSON == | |||
Après cette introduction voyons comment on construit un objet JSON à partir de sources variées. | |||
==== A partir d'une chaine ==== | |||
On l'a vu plus haut c'est la fonction '''loads''' qui fait le job.<syntaxhighlight lang="python3"> | |||
import json | |||
jsonobj=json.loads('{"id":3345,"values":[1,67,44,56,123]}') | |||
</syntaxhighlight>Qui construit :<syntaxhighlight lang="json"> | |||
{ | |||
"id": 3345, | |||
"values": [ | |||
1, | |||
67, | |||
44, | |||
56, | |||
123 | |||
] | |||
} | |||
</syntaxhighlight> | |||
==== A partir d'un fichier ==== | |||
Si on fichier disque contient le code JSON d'un objet on l'ouvre très simplement. | |||
Soit le fichier '''request.json''':<syntaxhighlight lang="json"> | |||
{ | |||
"id": 3, | |||
"createdDate": "2023-10-04T09:54:38.510+00:00", | |||
"servers": [ | |||
{ | |||
"hostname": "lifou", | |||
"IP": "192.168.1.10" | |||
}, | |||
{ | |||
"hostname": "mare", | |||
"IP": "192.168.1.11" | |||
}, | |||
{ | |||
"hostname": "ouvea", | |||
"IP": "192.168.1.12" | |||
} | |||
] | |||
} | |||
</syntaxhighlight>On le lits avec<syntaxhighlight lang="python3"> | |||
import json | |||
f=open('request.json') | |||
data=json.load(f) | |||
print (data["id"]) | |||
for s in data["servers"]: | |||
print (s["hostname"], s["IP"]) | |||
f.close() | |||
</syntaxhighlight>Qui va nous répondre :<syntaxhighlight lang="text"> | |||
3 | |||
lifou 192.168.1.10 | |||
mare 192.168.1.11 | |||
ouvea 192.168.1.12 | |||
</syntaxhighlight> | |||
== Convertir un objet Python en chaine JSON == | |||
La fonction <code>json.dumps</code> est la pour ça! | |||
On défini un objet Python<syntaxhighlight lang="python3"> | |||
import json | |||
obj={} | |||
obj["nom"]="PINON" | |||
obj["prenom"]="Jean" | |||
print (obj) | |||
print (json.dumps(obj)) | |||
</syntaxhighlight>On imprime l'objet Python puis la conversion en chaine JSON de l'objet Python . <syntaxhighlight lang="python3"> | |||
>>> print (obj) | |||
{'nom': 'PINON', 'prenom': 'Jean'} | |||
>>> print (json.dumps(obj)) | |||
{"nom": "PINON", "prenom": "Jean"} | |||
</syntaxhighlight>La différence est subtile mais les ' de python sont remplacées par des " de JSON. | |||
Version actuelle datée du 9 avril 2025 à 09:55
JSON c'est Javascript mais c'est aussi devenu un standard dans les échanges de données. Il faut savoir le traiter!
Modules utilisés
Il faut utiliser un module qui, en général, est fourni avec le pack de base de Python.
import json
Utilisation
Décodage (parsing)
La première chose qu'on désire faire c'est lire des données structurées en JSON avec Python.
Les listes (tableaux)
import json
# some JSON:
x = '[1,2,3,4]'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y[0])
Les dictionnaires (hashtables en perl ou en java)
import json
# some JSON:
x = '{"nom":"Raoul","age":45}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["nom"])
Importer du JSON
Après cette introduction voyons comment on construit un objet JSON à partir de sources variées.
A partir d'une chaine
On l'a vu plus haut c'est la fonction loads qui fait le job.
import json
jsonobj=json.loads('{"id":3345,"values":[1,67,44,56,123]}')
Qui construit :
{
"id": 3345,
"values": [
1,
67,
44,
56,
123
]
}
A partir d'un fichier
Si on fichier disque contient le code JSON d'un objet on l'ouvre très simplement.
Soit le fichier request.json:
{
"id": 3,
"createdDate": "2023-10-04T09:54:38.510+00:00",
"servers": [
{
"hostname": "lifou",
"IP": "192.168.1.10"
},
{
"hostname": "mare",
"IP": "192.168.1.11"
},
{
"hostname": "ouvea",
"IP": "192.168.1.12"
}
]
}
On le lits avec
import json
f=open('request.json')
data=json.load(f)
print (data["id"])
for s in data["servers"]:
print (s["hostname"], s["IP"])
f.close()
Qui va nous répondre :
3
lifou 192.168.1.10
mare 192.168.1.11
ouvea 192.168.1.12
Convertir un objet Python en chaine JSON
La fonction json.dumps est la pour ça!
On défini un objet Python
import json
obj={}
obj["nom"]="PINON"
obj["prenom"]="Jean"
print (obj)
print (json.dumps(obj))
On imprime l'objet Python puis la conversion en chaine JSON de l'objet Python .
>>> print (obj)
{'nom': 'PINON', 'prenom': 'Jean'}
>>> print (json.dumps(obj))
{"nom": "PINON", "prenom": "Jean"}
La différence est subtile mais les ' de python sont remplacées par des " de JSON.