File size: 2,620 Bytes
5ea2130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env python3

import argparse
import json
import re
import unicodedata
from collections import defaultdict
from pathlib import Path


def slugify(value: str) -> str:
    normalized = unicodedata.normalize("NFKD", value)
    ascii_value = normalized.encode("ascii", "ignore").decode("ascii")
    slug = re.sub(r"[^a-zA-Z0-9]+", "-", ascii_value.lower()).strip("-")
    return slug or "unknown"


def load_records(input_path: Path) -> list[dict]:
    with input_path.open("r", encoding="utf-8") as f:
        data = json.load(f)

    if not isinstance(data, list):
        raise ValueError(f"{input_path} must contain a top-level JSON array.")

    for index, item in enumerate(data):
        if not isinstance(item, dict):
            raise ValueError(f"Record at index {index} is not a JSON object.")

    return data


def group_records(records: list[dict]) -> dict[tuple[str, str], list[dict]]:
    grouped: dict[tuple[str, str], list[dict]] = defaultdict(list)

    for index, record in enumerate(records):
        domain = record.get("domain")
        sub_domain = record.get("sub_domain")

        if not domain or not sub_domain:
            raise ValueError(
                f"Record at index {index} is missing a non-empty 'domain' or 'sub_domain'."
            )

        grouped[(str(domain), str(sub_domain))].append(record)

    return grouped


def write_groups(grouped_records: dict[tuple[str, str], list[dict]], output_dir: Path) -> None:
    for (domain, sub_domain), records in grouped_records.items():
        domain_dir = output_dir / slugify(domain)
        output_path = domain_dir / f"{slugify(sub_domain)}.json"

        domain_dir.mkdir(parents=True, exist_ok=True)
        with output_path.open("w", encoding="utf-8") as f:
            json.dump(records, f, ensure_ascii=False, indent=2)
            f.write("\n")


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Split a JSON array into data/<domain>/<sub-domain>.json files."
    )
    parser.add_argument(
        "--input",
        type=Path,
        default=Path("data.json"),
        help="Path to the source JSON file. Default: data.json",
    )
    parser.add_argument(
        "--output-dir",
        type=Path,
        default=Path("data"),
        help="Directory where split files will be written. Default: data",
    )
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    records = load_records(args.input)
    grouped_records = group_records(records)
    write_groups(grouped_records, args.output_dir)


if __name__ == "__main__":
    main()