Daten mit JSON-Abfragen filtern
In diesem Schritt verwenden Sie die benutzerdefinierte Funktion json_extract
, um Daten basierend auf Werten innerhalb der JSON-Felder zu filtern.
Öffnen Sie die Datei json_extractor.py
erneut.
nano json_extractor.py
Ändern Sie die Datei json_extractor.py
, um eine Funktion zum Abfragen (querying) der Datenbank einzufügen:
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)
Dieser Code fügt eine filter_products
-Funktion hinzu, die einen Datenbankpfad (database path), einen JSON-Pfad und einen Wert als Eingabe entgegennimmt. Anschließend verbindet sie sich mit der Datenbank, registriert die Funktion json_extract
und führt eine Abfrage aus, um alle Produkte zu finden, bei denen der Wert am angegebenen JSON-Pfad mit dem angegebenen Wert übereinstimmt.
Speichern Sie die Datei und beenden Sie nano
.
Führen Sie nun das Python-Skript aus.
python3 json_extractor.py
Erwartete Ausgabe (Expected Output):
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"}}')]
Diese Ausgabe zeigt die Produkte, die den angegebenen Kriterien entsprechen.