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 '.'
doneHow 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
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.JSON to CSV ConverterConvert a JSON array of objects into CSV, using a column union and correct quoting of delimiters, quotes, and newlines.CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.CSV to Markdown TableConvert CSV data, including quoted fields with embedded commas and newlines, into a clean GitHub-flavored Markdown table with selectable alignment.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.