summaryrefslogtreecommitdiff
path: root/bin/hdump.py
blob: 7998996df2ef3a0b39e2ac815b5b0d5abc97a799 (plain)
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python3

import json
import sys
from typing import Any, Dict, List, Union

JSON = Union[str, int, float, bool, None, Dict[str, 'JSON'], List['JSON']]


def is_simple(entry: JSON) -> bool:
    if isinstance(entry, list):
        return len(entry) == 0
    if isinstance(entry, dict):
        return len(entry) == 0
    return True


def is_short(entry: Any, indent: int) -> bool:
    return (len(json.dumps(entry)) + indent) < 80


def hdumps(entry: JSON, *, _current_indent: int = 0) -> str:
    if is_short(entry, _current_indent):
        return json.dumps(entry)
    if isinstance(entry, list) and entry:
        result: str = "[ " + hdumps(entry[0],
                                    _current_indent=_current_indent + 2)
        for x in entry[1:]:
            result += "\n" + " " * _current_indent + ", "
            result += hdumps(x, _current_indent=_current_indent + 2)
        result += "\n" + " " * _current_indent + "]"
        return result
    if isinstance(entry, dict) and entry:
        result: str = "{ "
        is_first: bool = True
        for k in entry.keys():
            if not is_first:
                result += "\n" + " " * _current_indent + ", "
            result += json.dumps(k) + ":"
            if is_simple(entry[k]):
                result += " " + json.dumps(entry[k])
            elif is_short(entry[k], _current_indent + len(json.dumps(k)) + 4):
                result += " " + json.dumps(entry[k])
            else:
                result += "\n" + " " * _current_indent + "  "
                result += hdumps(entry[k], _current_indent=_current_indent + 2)
            is_first = False
        result += "\n" + " " * _current_indent + "}"
        return result
    return json.dumps(entry)


if __name__ == "__main__":
    data = json.load(sys.stdin)
    print(hdumps(data))