Skip to content

Commit ee76b04

Browse files
Merge pull request #114 from Seikened/fer_leon
feat: agregar opciones de serialización JSON y formato de archivo
2 parents 3380862 + fd13d46 commit ee76b04

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

src/sdialog/__init__.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -453,7 +453,7 @@ def prompt(self) -> str:
453453
"""Generates a prompt string for the entire dialogue."""
454454
return json.dumps(self.json()["turns"], indent=2)
455455

456-
def json(self, string: bool = False, indent: int = 2):
456+
def json(self, string: bool = False, indent: int = 2,ensure_ascii: bool = False):
457457
"""
458458
Serializes the dialogue to JSON.
459459
@@ -466,7 +466,7 @@ def json(self, string: bool = False, indent: int = 2):
466466
"""
467467
data = self.model_dump()
468468
make_serializable(data)
469-
return json.dumps(data, indent=indent) if string else data
469+
return json.dumps(data, indent=indent, ensure_ascii=ensure_ascii) if string else data
470470

471471
def print(self, *a, **kw):
472472
"""
@@ -483,7 +483,7 @@ def print(self, *a, **kw):
483483
"""
484484
_print_dialog(self, *a, **kw)
485485

486-
def to_file(self, path: str = None, type: str = "auto", makedir: bool = True, overwrite: bool = True):
486+
def to_file(self, path: str = None, type: str = "auto", makedir: bool = True, overwrite: bool = True, human_readable: bool = False):
487487
"""
488488
Saves the dialogue to a file in JSON, CSV, or plain text format.
489489
@@ -495,6 +495,8 @@ def to_file(self, path: str = None, type: str = "auto", makedir: bool = True, ov
495495
:type makedir: bool
496496
:param overwrite: If False and the file exists, raise FileExistsError instead of overwriting.
497497
:type overwrite: bool
498+
:param human_readable: If True and type is "json", pretty-print the JSON output.
499+
:type human_readable: bool
498500
"""
499501
if not path:
500502
if self._path:
@@ -514,9 +516,9 @@ def to_file(self, path: str = None, type: str = "auto", makedir: bool = True, ov
514516
if not overwrite and os.path.exists(path):
515517
raise FileExistsError(f"File '{path}' already exists. Use 'overwrite=True' to overwrite it.")
516518

517-
with open(path, "w", newline='') as writer:
519+
with open(path, "w", newline='', encoding='utf-8') as writer:
518520
if type == "json":
519-
writer.write(self.json(string=True))
521+
writer.write(self.json(string=True, ensure_ascii=not human_readable))
520522
elif type in ["csv", "tsv"]:
521523
# set delimiter based on desired type
522524
delimiter = {"csv": ",", "tsv": "\t"}[type]

0 commit comments

Comments
 (0)