File: json_output_adapter.py

package info (click to toggle)
cli-helpers 2.7.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 356 kB
  • sloc: python: 2,208; makefile: 16
file content (37 lines) | stat: -rw-r--r-- 1,014 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# -*- coding: utf-8 -*-
"""A JSON data output adapter"""

from decimal import Decimal
from itertools import chain
import json

from .preprocessors import bytes_to_string

supported_formats = ("jsonl", "jsonl_escaped")
preprocessors = (bytes_to_string,)


class CustomEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, Decimal):
            return float(o)
        else:
            return super(CustomEncoder, self).default(o)


def adapter(data, headers, table_format="jsonl", **_kwargs):
    """Wrap the formatting inside a function for TabularOutputFormatter."""
    if table_format == "jsonl":
        ensure_ascii = False
    elif table_format == "jsonl_escaped":
        ensure_ascii = True
    else:
        raise ValueError("Invalid table_format specified.")

    for row in chain(data):
        yield json.dumps(
            dict(zip(headers, row, strict=True)),
            cls=CustomEncoder,
            separators=(",", ":"),
            ensure_ascii=ensure_ascii,
        )