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.

BashData Integrity

Code

bashsnippet
22 lines
#!/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 '.'
    done

How it works

Strict mode (set -euo pipefail) makes failures loud — an unset variable or a failing pipeline stage aborts the script instead of being swallowed.

The work is delegated to readonly, awk and value, chained through 2 pipes so each stage’s output feeds the next.

Core lines under the microscope

for (i = 1; i <= NF; i++) header[i] = $i
for (i = 1; i <= NF; i++) {
| while IFS= read -r line; do
    printf '{%s}\n' "${line}" | jq -c '.'

Interactive Tools for This Topic

FAQ

Does the script stop on the first error?
Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Which external commands does the script rely on?
`readonly`, `awk`, `value` must be available on the PATH environment variable; everything else is shell built-in syntax.