| 1 |
#!/usr/bin/env python |
| 2 |
# |
| 3 |
# ===- csv2json.py - Static Analyzer test helper ---*- python -*-===# |
| 4 |
# |
| 5 |
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 6 |
# See https://llvm.org/LICENSE.txt for license information. |
| 7 |
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 8 |
# |
| 9 |
# ===------------------------------------------------------------------------===# |
| 10 |
|
| 11 |
r""" |
| 12 |
Clang Static Analyzer test helper |
| 13 |
================================= |
| 14 |
|
| 15 |
This script converts a CSV file to a JSON file with a specific structure. |
| 16 |
|
| 17 |
The JSON file contains a single dictionary. The keys of this dictionary |
| 18 |
are taken from the first column of the CSV. The values are dictionaries |
| 19 |
themselves, mapping the CSV header names (except the first column) to |
| 20 |
the corresponding row values. |
| 21 |
|
| 22 |
|
| 23 |
Usage: |
| 24 |
csv2json.py <source-file> |
| 25 |
|
| 26 |
Example: |
| 27 |
// RUN: %csv2json.py %t | FileCheck %s |
| 28 |
""" |
| 29 |
|
| 30 |
import csv |
| 31 |
import sys |
| 32 |
import json |
| 33 |
|
| 34 |
|
| 35 |
def csv_to_json_dict(csv_filepath): |
| 36 |
""" |
| 37 |
Args: |
| 38 |
csv_filepath: The path to the input CSV file. |
| 39 |
|
| 40 |
Raises: |
| 41 |
FileNotFoundError: If the CSV file does not exist. |
| 42 |
csv.Error: If there is an error parsing the CSV file. |
| 43 |
Exception: For any other unexpected errors. |
| 44 |
""" |
| 45 |
try: |
| 46 |
with open(csv_filepath, "r", encoding="utf-8") as csvfile: |
| 47 |
reader = csv.reader(csvfile, skipinitialspace=True) |
| 48 |
|
| 49 |
# Read the header row (column names) |
| 50 |
try: |
| 51 |
header = next(reader) |
| 52 |
except StopIteration: # Handle empty CSV file |
| 53 |
json.dumps({}, indent=2) # write an empty dict |
| 54 |
return |
| 55 |
|
| 56 |
# handle a csv file that contains no rows, not even a header row. |
| 57 |
if not header: |
| 58 |
json.dumps({}, indent=2) |
| 59 |
return |
| 60 |
|
| 61 |
header_length = len(header) |
| 62 |
other_column_names = header[1:] |
| 63 |
|
| 64 |
data_dict = {} |
| 65 |
|
| 66 |
for row in reader: |
| 67 |
if len(row) != header_length: |
| 68 |
raise csv.Error("Inconsistent CSV file") |
| 69 |
exit(1) |
| 70 |
|
| 71 |
key = row[0] |
| 72 |
value_map = {} |
| 73 |
|
| 74 |
for i, col_name in enumerate(other_column_names): |
| 75 |
# +1 to skip the first column |
| 76 |
value_map[col_name] = row[i + 1].strip() |
| 77 |
|
| 78 |
data_dict[key] = value_map |
| 79 |
|
| 80 |
return json.dumps(data_dict, indent=2) |
| 81 |
|
| 82 |
except FileNotFoundError: |
| 83 |
raise FileNotFoundError(f"Error: CSV file not found at {csv_filepath}") |
| 84 |
except csv.Error as e: |
| 85 |
raise csv.Error(f"Error parsing CSV file: {e}") |
| 86 |
except Exception as e: |
| 87 |
raise Exception(f"An unexpected error occurred: {e}") |
| 88 |
|
| 89 |
|
| 90 |
def main(): |
| 91 |
"""Example usage with error handling.""" |
| 92 |
csv_file = sys.argv[1] |
| 93 |
|
| 94 |
try: |
| 95 |
print(csv_to_json_dict(csv_file)) |
| 96 |
except (FileNotFoundError, csv.Error, Exception) as e: |
| 97 |
print(str(e)) |
| 98 |
except: |
| 99 |
print("An error occured") |
| 100 |
|
| 101 |
|
| 102 |
if __name__ == "__main__": |
| 103 |
main() |