From fd13d46c463e121978eecdeccb636761e45462f7 Mon Sep 17 00:00:00 2001 From: Fernando Leon Franco Date: Mon, 24 Nov 2025 12:19:05 -0600 Subject: [PATCH] =?UTF-8?q?feat:=20agregar=20opciones=20de=20serializaci?= =?UTF-8?q?=C3=B3n=20JSON=20y=20formato=20de=20archivo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Añadir parámetro `ensure_ascii` a la función `json` para controlar la codificación. - Añadir parámetro `human_readable` a la función `to_file` para permitir la impresión legible del JSON. - Actualizar la escritura de archivos JSON para usar `utf-8` como codificación. --- src/sdialog/__init__.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/sdialog/__init__.py b/src/sdialog/__init__.py index 91f02cd..7d32399 100644 --- a/src/sdialog/__init__.py +++ b/src/sdialog/__init__.py @@ -453,7 +453,7 @@ def prompt(self) -> str: """Generates a prompt string for the entire dialogue.""" return self.json(string=True) - def json(self, string: bool = False, indent: int = 2): + def json(self, string: bool = False, indent: int = 2,ensure_ascii: bool = False): """ Serializes the dialogue to JSON. @@ -466,7 +466,7 @@ def json(self, string: bool = False, indent: int = 2): """ data = self.model_dump() make_serializable(data) - return json.dumps(data, indent=indent) if string else data + return json.dumps(data, indent=indent, ensure_ascii=ensure_ascii) if string else data def print(self, *a, **kw): """ @@ -483,7 +483,7 @@ def print(self, *a, **kw): """ _print_dialog(self, *a, **kw) - def to_file(self, path: str = None, type: str = "auto", makedir: bool = True, overwrite: bool = True): + def to_file(self, path: str = None, type: str = "auto", makedir: bool = True, overwrite: bool = True, human_readable: bool = False): """ Saves the dialogue to a file in JSON, CSV, or plain text format. @@ -495,6 +495,8 @@ def to_file(self, path: str = None, type: str = "auto", makedir: bool = True, ov :type makedir: bool :param overwrite: If False and the file exists, raise FileExistsError instead of overwriting. :type overwrite: bool + :param human_readable: If True and type is "json", pretty-print the JSON output. + :type human_readable: bool """ if not path: if self._path: @@ -514,9 +516,9 @@ def to_file(self, path: str = None, type: str = "auto", makedir: bool = True, ov if not overwrite and os.path.exists(path): raise FileExistsError(f"File '{path}' already exists. Use 'overwrite=True' to overwrite it.") - with open(path, "w", newline='') as writer: + with open(path, "w", newline='', encoding='utf-8') as writer: if type == "json": - writer.write(self.json(string=True)) + writer.write(self.json(string=True, ensure_ascii=not human_readable)) elif type in ["csv", "tsv"]: # set delimiter based on desired type delimiter = {"csv": ",", "tsv": "\t"}[type]