Files
HP_InHand_IG502/code snippets/csvToJSON.py
2026-01-22 10:40:54 -06:00

79 lines
2.1 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
csv_to_json.py
Convert a CSV into a JSON array where each element is
{
"<value from column 2>": {
"data_type": "<value from column 4>",
"tag_name": "<value from column 2>"
}
}
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 UTF8, 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" (casesensitive)
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 prettyprinted 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]} <input.csv> <output.json>", 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)