Fundamentals 4 min read

Convert JSON to CSV with jq: A Step‑by‑Step Tutorial

This tutorial demonstrates how to use the jq command‑line tool to extract an array of objects from a JSON file, reshape the data into a two‑column format, and output it as properly formatted CSV, including handling of quoting and raw output options.

FunTester
FunTester
FunTester
Convert JSON to CSV with jq: A Step‑by‑Step Tutorial

Part 1: Extract Data

We start by reading FunTester.json and filtering the article array using the jq filter '.article[]'. This returns each object in the array as separate JSON objects rather than a single JSON array.

cat FunTester.json | jq '.article[]'
{
  "author": "tester1",
  "title": "ApiTest"
}
{
  "author": "tester2",
  "title": "performanceTest"
}

If we omit the [] and use '.article', jq returns the whole array wrapped in brackets.

cat FunTester.json | jq '.article'
[
  {
    "author": "tester1",
    "title": "ApiTest"
  },
  {
    "author": "tester2",
    "title": "performanceTest"
  }
]

Part 2: Assemble Data

Next we transform each JSON object into a two‑element array containing the author and title fields. The filter '.article[] | [.author, .title]' produces a stream of arrays.

cat FunTester.json | jq '.article[] | [.author, .title]'
[
  "tester1",
  "ApiTest"
]
[
  "tester2",
  "performanceTest"
]

The resulting arrays can later be joined into CSV rows.

Part 3: Output CSV

Finally we apply the @csv operator to format each array as a CSV line. By default jq escapes double quotes, so the output looks like "tester1","ApiTest". To obtain raw CSV without the extra escaping, we add the -r (raw output) flag.

# With default escaping
cat FunTester.json | jq '.article[] | [.author, .title] | @csv'
"\"tester1\",\"ApiTest\""
"\"tester2\",\"performanceTest\""

# Raw CSV output
cat FunTester.json | jq -r '.article[] | [.author, .title] | @csv'
"tester1","ApiTest"
"tester2","performanceTest"
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JSONShellcommand-linejqCSVdata transformation
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.