Skip to content

Instantly share code, notes, and snippets.

@brandonrobertz
Created December 11, 2024 22:46
Show Gist options
  • Select an option

  • Save brandonrobertz/2dfe155ff93ae6120505379a9533fbc1 to your computer and use it in GitHub Desktop.

Select an option

Save brandonrobertz/2dfe155ff93ae6120505379a9533fbc1 to your computer and use it in GitHub Desktop.
Pure Python CSV to JSON Script
#!/usr/bin/env python3
import argparse
import csv
import json
from typing import List
from typing import Dict
from typing import Iterable
class Csv2Json(object):
def run(self,
csv_path: str,
json_path: str,
has_header: bool = False,
pretty_print: bool = False,
delimiter: str = ",",
) -> None:
"""
Execute csv 2 json conversion.
Args:
csv_path (str): Path to the CSV input file.
json_path (str): Path to the JSON output file.
has_header (bool): Does the CSV file have a header.
pretty_print (bool): Pretty JSON formatting enabled.
delimiter (str): Delimiter for CSV (defaults to ",")
"""
csv_array: List = []
with open(
csv_path, newline="", encoding="utf-8", errors="ignore"
) as csv_file:
csv_content: Iterable = csv.reader(csv_file, delimiter=delimiter)
for row in csv_content:
csv_array.append(row)
header: List[str] = []
json_struct: List = []
if has_header:
header = csv_array.pop(0)
for row in csv_array:
temp_struct: Dict = {}
for index, element in enumerate(header):
temp_struct[element] = row[index]
json_struct.append(temp_struct)
if not has_header:
for row in csv_array:
json_struct.append(row)
with open(json_path, "w") as json_file:
if pretty_print:
json.dump(json_struct, json_file, indent=2)
else:
json.dump(json_struct, json_file)
def main():
parser: argparse.ArgumentParser = argparse.ArgumentParser()
parser.add_argument("csv", help="CSV input file path", type=str)
parser.add_argument("json", help="JSON otput path", type=str)
parser.add_argument(
"--delimiter",
help="Character delimiter to use",
default=',',
type=lambda x: x.encode().decode('unicode_escape')
)
parser.add_argument(
"--has-header",
help="Does the CSV file have a header",
action="store_true"
)
parser.add_argument(
"--pretty-print",
help="JSON should be pretty formated",
action="store_true"
)
args: argparse.Namespace = parser.parse_args()
Csv2Json().run(args.csv, args.json, args.has_header, args.pretty_print, delimiter=args.delimiter)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment