codex/files-formats/json_orjson.cat
# Parsing JSON rapide avec orjson
# orjson est 3-10x plus rapide que le json stdlib
# Il travaille nativement avec des bytes (pas de strings)
#
# Exécuter: catnip -m orjson -m tempfile -m pathlib -m shutil -m datetime json_orjson.cat
orjson = import("orjson")
tempfile = import("tempfile")
pathlib = import("pathlib")
shutil = import("shutil")
datetime = import("datetime")
# Parsing depuis bytes (usage natif)
print("⇒ Parsing bytes (natif orjson)")
json_bytes = '{"name": "Alice", "age": 30, "active": true}'.encode("utf-8")
data = orjson.loads(json_bytes)
print(" Name:", data["name"])
print(" Age:", data["age"])
# Parsing depuis string (converti en bytes automatiquement)
print("\n⇒ Parsing string")
json_str = '{"status": "ok", "code": 200}'
response = orjson.loads(json_str)
print(" Status:", response["status"])
# Structures complexes
print("\n⇒ Structure complexe")
api_json = '{"users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]}'.encode("utf-8")
api_response = orjson.loads(api_json)
for user in api_response["users"] {
print(" -", user["name"], "(id:", user["id"], ")")
}
# Sérialisation -> bytes
print("\n⇒ Sérialisation (retourne bytes)")
obj = dict(message="Hello", count=42)
serialized = orjson.dumps(obj)
print(" Type:", serialized.__class__.__name__)
print(" Raw:", serialized)
print(" Decoded:", serialized.decode("utf-8"))
# Construction dynamique avec affectation par index
print("\n⇒ Construction dynamique")
config = dict()
config["host"] = "localhost"
config["port"] = 8080
config["ssl"] = True
result = orjson.dumps(config)
print(" Bytes:", result)
# Dates (orjson gère les dates nativement)
print("\n⇒ Dates natives")
event = dict(event="meeting", date=datetime.date(2024, 3, 15))
print(" ", orjson.dumps(event))
# Écriture/lecture fichier avec bytes
temp_dir = pathlib.Path(tempfile.mkdtemp())
json_file = temp_dir / "data.json"
records = list(
dict(id=1, value=10),
dict(id=2, value=20),
dict(id=3, value=30),
)
print("\n⇒ Écriture fichier (bytes)")
json_file.write_bytes(orjson.dumps(records))
print(" Fichier:", json_file)
print("\n⇒ Relecture fichier (bytes)")
reloaded = orjson.loads(json_file.read_bytes())
for r in reloaded {
print(" id:", r["id"], "value:", r["value"])
}
# Nettoyage
shutil.rmtree(str(temp_dir))
print("\n⇒ Nettoyage effectué")