Update JSONDict for PosixPath to String (#16522)
This commit is contained in:
parent
250eaa857a
commit
538c8215f3
1 changed files with 9 additions and 2 deletions
|
|
@ -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…
Add table
Add a link
Reference in a new issue