From 8375ccf2895ea6d626e9f611899f32bfc0ed76b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Saugat=20Pachhai=20=28=E0=A4=B8=E0=A5=8C=E0=A4=97=E0=A4=BE?= =?UTF-8?q?=E0=A4=A4=29?= Date: Wed, 6 Oct 2021 10:35:47 +0545 Subject: [PATCH] json: add support for default encoder --- rich/json.py | 23 ++++++++++++++++------- tests/test_json.py | 8 ++++++++ 2 files changed, 24 insertions(+), 7 deletions(-) create mode 100644 tests/test_json.py diff --git a/rich/json.py b/rich/json.py index 6266c92a..a63f1754 100644 --- a/rich/json.py +++ b/rich/json.py @@ -1,5 +1,5 @@ from json import loads, dumps -from typing import Any +from typing import Any, Callable, Optional from .text import Text from .highlighter import JSONHighlighter, NullHighlighter @@ -23,17 +23,26 @@ class JSON: self.text.overflow = None @classmethod - def from_data(cls, data: Any, indent: int = 2, highlight: bool = True) -> "JSON": + def from_data( + cls, + data: Any, + indent: int = 2, + highlight: bool = True, + default: Optional[Callable[[Any], Any]] = None, + ) -> "JSON": """Encodes a JSON object from arbitrary data. + Args: + data (Any): An object that may be encoded in to JSON + indent (int, optional): Number of characters to indent by. Defaults to 2. + highlight (bool, optional): Enable highlighting. Defaults to True. + default (Callable, optional): Optional callable which will be called for objects that cannot be serialized. Defaults to None. + Returns: - Args: - data (Any): An object that may be encoded in to JSON - indent (int, optional): Number of characters to indent by. Defaults to 2. - highlight (bool, optional): Enable highlighting. Defaults to True. + JSON: New JSON object from the given data. """ json_instance: "JSON" = cls.__new__(cls) - json = dumps(data, indent=indent) + json = dumps(data, indent=indent, default=default) highlighter = JSONHighlighter() if highlight else NullHighlighter() json_instance.text = highlighter(json) json_instance.text.no_wrap = True diff --git a/tests/test_json.py b/tests/test_json.py new file mode 100644 index 00000000..7571b0a3 --- /dev/null +++ b/tests/test_json.py @@ -0,0 +1,8 @@ +from rich.json import JSON +import datetime + + +def test_print_json_data_with_default(): + date = datetime.date(2021, 1, 1) + json = JSON.from_data({"date": date}, default=lambda d: d.isoformat()) + assert str(json.text) == '{\n "date": "2021-01-01"\n}'