Skip to content

Instantly share code, notes, and snippets.

@leagueofperez
Last active October 1, 2024 19:22
Show Gist options
  • Save leagueofperez/f75a9061aa60908f4f87ecf7a78f9434 to your computer and use it in GitHub Desktop.
Save leagueofperez/f75a9061aa60908f4f87ecf7a78f9434 to your computer and use it in GitHub Desktop.
Convert CSV file to JSON file
#!/bin/bash
file="$1"
script_name=$(basename "$0") # Get the script name without the path
# Function to convert CSV to JSON
csvtojson() {
python3 -c "
import csv, json, sys
with open('$file') as f:
print(json.dumps([dict(row) for row in csv.DictReader(f)]))
" | jq . >"${basename_file}.json"
}
# Check if a file is specified
if [ "$#" -ne 1 ]; then
echo "Usage: $script_name <csv_file>"
exit 1
fi
# Check if the file exists
if [ ! -f "$file" ]; then
echo "File not found: $file"
exit 2
fi
# Check if the file is a CSV
if [[ "$file" == *.csv ]]; then
basename_file=$(basename "$file" .csv) # Use basename to get the file name without extension
if csvtojson; then
echo "${basename_file}.json created from ${file}"
else
echo "Conversion of ${file} failed"
exit 3
fi
else
echo "The specified file ${file} is not a CSV file"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment