Filtrer les données à l'aide de requêtes JSON
Dans cette étape, vous utiliserez la fonction personnalisée json_extract
pour filtrer les données en fonction des valeurs contenues dans les champs JSON.
Ouvrez à nouveau le fichier json_extractor.py
.
nano json_extractor.py
Modifiez le fichier json_extractor.py
pour inclure une fonction permettant d'interroger la base de données :
import sqlite3
import json
def json_extract(json_str, path):
try:
json_data = json.loads(json_str)
path_components = path.split('.')
value = json_data
for component in path_components:
value = value.get(component)
return value
except (json.JSONDecodeError, AttributeError, TypeError):
return None
def connect_db(db_path):
conn = sqlite3.connect(db_path)
conn.create_function("json_extract", 2, json_extract)
return conn
def filter_products(db_path, json_path, value):
conn = connect_db(db_path)
cursor = conn.cursor()
query = f"SELECT * FROM products WHERE json_extract(details, '{json_path}') = '{value}'"
cursor.execute(query)
results = cursor.fetchall()
conn.close()
return results
if __name__ == '__main__':
## Example usage:
dell_products = filter_products('mydatabase.db', 'brand', 'Dell')
print("Products with brand 'Dell':", dell_products)
intel_products = filter_products('mydatabase.db', 'specs.cpu', 'Intel i7')
print("Products with CPU 'Intel i7':", intel_products)
Ce code ajoute une fonction filter_products
qui prend un chemin de base de données (database path), un chemin JSON (JSON path) et une valeur en entrée. Il se connecte ensuite à la base de données, enregistre la fonction json_extract
et exécute une requête pour trouver tous les produits où la valeur au chemin JSON spécifié correspond à la valeur donnée.
Enregistrez le fichier et quittez nano
.
Maintenant, exécutez le script Python.
python3 json_extractor.py
Résultat attendu :
Products with brand 'Dell': [(1, 'Laptop', '{"brand": "Dell", "model": "XPS 13", "specs": {"cpu": "Intel i7", "memory": "16GB", "storage": "512GB SSD"}}')]
Products with CPU 'Intel i7': [(1, 'Laptop', '{"brand": "Dell", "model": "XPS 13", "specs": {"cpu": "Intel i7", "memory": "16GB", "storage": "512GB SSD"}}')]
Ce résultat montre les produits qui correspondent aux critères spécifiés.