json: add support for default encoder

This commit is contained in:
Saugat Pachhai (सौगात) 2021-10-06 10:35:47 +05:45
parent 473eac577f
commit 8375ccf289
No known key found for this signature in database
GPG key ID: 424BDDBA58C0953D
2 changed files with 24 additions and 7 deletions

View file

@ -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

8
tests/test_json.py Normal file
View file

@ -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}'