Update JSONDict for PosixPath to String (#16522)

pull/16470/head^2
Glenn Jocher 5 months ago committed by GitHub
parent 250eaa857a
commit 538c8215f3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 11
      ultralytics/utils/__init__.py

@ -1091,10 +1091,17 @@ class JSONDict(dict):
try: try:
self.file_path.parent.mkdir(parents=True, exist_ok=True) self.file_path.parent.mkdir(parents=True, exist_ok=True)
with open(self.file_path, "w") as f: with open(self.file_path, "w") as f:
json.dump(dict(self), f, indent=2) json.dump(dict(self), f, indent=2, default=self._json_default)
except Exception as e: except Exception as e:
print(f"Error writing to {self.file_path}: {e}") print(f"Error writing to {self.file_path}: {e}")
@staticmethod
def _json_default(obj):
"""Handle JSON serialization of Path objects."""
if isinstance(obj, Path):
return str(obj)
raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
def __setitem__(self, key, value): def __setitem__(self, key, value):
"""Store a key-value pair and persist to disk.""" """Store a key-value pair and persist to disk."""
with self.lock: with self.lock:
@ -1109,7 +1116,7 @@ class JSONDict(dict):
def __str__(self): def __str__(self):
"""Return a pretty-printed JSON string representation of the dictionary.""" """Return a pretty-printed JSON string representation of the dictionary."""
return f'JSONDict("{self.file_path}"):\n{json.dumps(dict(self), indent=2, ensure_ascii=False)}' return f'JSONDict("{self.file_path}"):\n{json.dumps(dict(self), indent=2, ensure_ascii=False, default=self._json_default)}'
def update(self, *args, **kwargs): def update(self, *args, **kwargs):
"""Update the dictionary and persist changes.""" """Update the dictionary and persist changes."""

Loading…
Cancel
Save