| 1 |
|
| 2 |
"""A JSON data output adapter""" |
| 3 |
|
| 4 |
from decimal import Decimal |
| 5 |
from itertools import chain |
| 6 |
import json |
| 7 |
|
| 8 |
from .preprocessors import bytes_to_string |
| 9 |
|
| 10 |
supported_formats = ("jsonl", "jsonl_escaped") |
| 11 |
preprocessors = (bytes_to_string,) |
| 12 |
|
| 13 |
|
| 14 |
class CustomEncoder(json.JSONEncoder): |
| 15 |
def default(self, o): |
| 16 |
if isinstance(o, Decimal): |
| 17 |
return float(o) |
| 18 |
else: |
| 19 |
return super(CustomEncoder, self).default(o) |
| 20 |
|
| 21 |
|
| 22 |
def adapter(data, headers, table_format="jsonl", **_kwargs): |
| 23 |
"""Wrap the formatting inside a function for TabularOutputFormatter.""" |
| 24 |
if table_format == "jsonl": |
| 25 |
ensure_ascii = False |
| 26 |
elif table_format == "jsonl_escaped": |
| 27 |
ensure_ascii = True |
| 28 |
else: |
| 29 |
raise ValueError("Invalid table_format specified.") |
| 30 |
|
| 31 |
for row in chain(data): |
| 32 |
yield json.dumps( |
| 33 |
dict(zip(headers, row, strict=True)), |
| 34 |
cls=CustomEncoder, |
| 35 |
separators=(",", ":"), |
| 36 |
ensure_ascii=ensure_ascii, |
| 37 |
) |