mirror of
https://github.com/Textualize/rich.git
synced 2025-08-04 18:18:22 +00:00
json: add support for default encoder
This commit is contained in:
parent
473eac577f
commit
8375ccf289
2 changed files with 24 additions and 7 deletions
23
rich/json.py
23
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
|
||||
|
|
8
tests/test_json.py
Normal file
8
tests/test_json.py
Normal 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}'
|
Loading…
Add table
Add a link
Reference in a new issue