-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcsv-to-json
More file actions
executable file
·61 lines (50 loc) · 2 KB
/
Copy pathcsv-to-json
File metadata and controls
executable file
·61 lines (50 loc) · 2 KB
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
#!/usr/bin/env --split-string=uv --quiet run --script # pylint: disable=invalid-name
# -*- coding: utf-8 -*-
#
# # © 2025, The Arizona Board of Regents on behalf of The University of Arizona.
# For license information, see https://cyverse.org/license.
"""
CSV to JSON-SEQ converter.
This module provides functionality to convert CSV data from stdin to JSON Sequence
format (RFC 7464), writing the result to stdout. Each JSON record is prefixed with
RS (0x1E) and followed by LF. The CSV headers are used as JSON object keys.
"""
import csv
import json
import sys
def convert_csv_to_json_seq() -> None:
"""
Convert CSV data from stdin to JSON Sequence format and write to stdout.
The function reads CSV formatted data from standard input and converts each row
to a JSON object. Each object is prefixed with RS (0x1E) and followed by LF,
conforming to RFC 7464 JSON Sequence format.
Raises:
csv.Error: If there is an error reading the CSV input
TypeError: If there is an error encoding the data as JSON
"""
try:
reader = csv.DictReader(sys.stdin)
# Process each row individually to create JSON-SEQ format
for row in reader:
record = {
"username": row["username"],
"full_name": row["full_name"],
"last_activity": row["last_activity"],
"file_count": int(row["file_count"]),
"file_volume": int(row["file_volume"]),
"mail": row["mail"],
}
# Write Record Separator (RS)
sys.stdout.write('\x1E')
# Write JSON record
json.dump(record, sys.stdout)
# Write Line Feed (LF)
sys.stdout.write('\n')
except csv.Error as err:
print(f"Error reading CSV data: {err}", file=sys.stderr)
sys.exit(1)
except TypeError as err:
print(f"Error encoding JSON: {err}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
convert_csv_to_json_seq()