#!/usr/bin/env python3 """ csv_to_json.py Convert a CSV into a JSON array where each element is { "": { "data_type": "", "tag_name": "" } } Only rows whose first column is exactly "TAG" are included. """ import csv import json import sys from pathlib import Path def csv_to_tag_json(csv_path: Path, json_path: Path) -> None: """ Parameters ---------- csv_path : Path Path to the source CSV file. json_path : Path Path where the output JSON should be written. """ tag_rows = {} # open the CSV file. Assume UTF‑8, but you can change if needed. with csv_path.open(newline='', encoding='utf-8') as f: reader = csv.reader(f) for row_index, row in enumerate(reader, start=1): # guard against empty rows if not row: continue # Ensure we have at least 5 columns (index 0..4) if len(row) < 5: print(f"⚠️ Skipping line {row_index}: not enough columns", file=sys.stderr) continue # Row 0 must be exactly "TAG" (case‑sensitive) if row[0] != "TAG": continue tag_name = row[2] data_type = row[4] # Build the object exactly as you asked tag_rows[tag_name] = { "data_type": data_type, "tag_name": tag_name } # Write the list of objects as pretty‑printed JSON with json_path.open('w', encoding='utf-8') as f: json.dump(tag_rows, f, indent=2, ensure_ascii=False) print(f"✅ Wrote {len(tag_rows)} rows to {json_path}") if __name__ == "__main__": # Usage: python csv_to_json.py input.csv output.json if len(sys.argv) != 3: print(f"Usage: {sys.argv[0]} ", file=sys.stderr) sys.exit(1) csv_file = Path(sys.argv[1]) json_file = Path(sys.argv[2]) if not csv_file.exists(): print(f"❌ File not found: {csv_file}", file=sys.stderr) sys.exit(1) csv_to_tag_json(csv_file, json_file)