Travailler avec les données JSON
Maintenant que nous savons comment importer correctement le module JSON, explorons comment l'utiliser pour les opérations JSON courantes.
Création d'un exemple JSON complet
Créez un nouveau fichier nommé json_operations.py avec le contenu suivant :
## Complete example of working with JSON in Python
import json
## 1. Converting Python object to JSON string (serialization)
user = {
"name": "Charlie",
"age": 28,
"is_student": False,
"courses": ["Python", "Data Science", "Web Development"],
"address": {
"street": "123 Tech Lane",
"city": "Boston",
"zipcode": "02101"
}
}
## Convert Python dictionary to JSON string
json_string = json.dumps(user, indent=2)
print("JSON string created from Python object:")
print(json_string)
print("\n" + "-"*50 + "\n")
## 2. Parse JSON string to Python object (deserialization)
parsed_user = json.loads(json_string)
print("Python object created from JSON string:")
print("Name:", parsed_user["name"])
print("Age:", parsed_user["age"])
print("Courses:", parsed_user["courses"])
print("City:", parsed_user["address"]["city"])
print("\n" + "-"*50 + "\n")
## 3. Writing JSON to a file
with open("/home/labex/project/user_data.json", "w") as json_file:
json.dump(user, json_file, indent=2)
print("JSON data written to user_data.json")
## 4. Reading JSON from a file
with open("/home/labex/project/user_data.json", "r") as json_file:
loaded_user = json.load(json_file)
print("JSON data loaded from file. User name:", loaded_user["name"])
Ce script démontre quatre opérations JSON courantes :
- Conversion d'un objet Python en une chaîne JSON en utilisant
json.dumps()
- Analyse d'une chaîne JSON en un objet Python en utilisant
json.loads()
- Écriture de données JSON dans un fichier en utilisant
json.dump()
- Lecture de données JSON à partir d'un fichier en utilisant
json.load()
Exécutez le script :
python3 /home/labex/project/json_operations.py
Vous devriez voir une sortie similaire à :
JSON string created from Python object:
{
"name": "Charlie",
"age": 28,
"is_student": false,
"courses": [
"Python",
"Data Science",
"Web Development"
],
"address": {
"street": "123 Tech Lane",
"city": "Boston",
"zipcode": "02101"
}
}
--------------------------------------------------
Python object created from JSON string:
Name: Charlie
Age: 28
Courses: ['Python', 'Data Science', 'Web Development']
City: Boston
--------------------------------------------------
JSON data written to user_data.json
JSON data loaded from file. User name: Charlie
Le script a également créé un fichier nommé user_data.json. Examinons son contenu :
cat /home/labex/project/user_data.json
Vous devriez voir les données JSON formatées avec une indentation correcte :
{
"name": "Charlie",
"age": 28,
"is_student": false,
"courses": ["Python", "Data Science", "Web Development"],
"address": {
"street": "123 Tech Lane",
"city": "Boston",
"zipcode": "02101"
}
}
Vous avez maintenant appris avec succès comment travailler avec les données JSON en Python, y compris comment éviter l'erreur NameError: name 'json' is not defined en important correctement le module.