Convert CSV to JSON With jq
Turn a header CSV into newline-delimited JSON by streaming rows through awk and jq, preserving the header as field names.
Code
#!/usr/bin/env bash
set -euo pipefail
readonly INPUT="${1:?csv file required}"
awk -F',' '
NR == 1 {
for (i = 1; i <= NF; i++) header[i] = $i
next
}
{
for (i = 1; i <= NF; i++) {
value = $i
gsub(/"/, "\\\"", value)
printf "%s\"%s\":\"%s\"", (i > 1 ? "," : ""), header[i], value
}
printf "\n"
}
' "${INPUT}" \
| while IFS= read -r line; do
printf '{%s}\n' "${line}" | jq -c '.'
doneReport a problem with this exampleOpens a pre-filled issue on GitHub.