0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Read JSON Using jq Command

Use jq '.key' filename.json in a Bash script to read JSON values; for example, jq '.name' data.json extracts the 'name' field.
📋

Examples

Input{"name":"Alice"}
Output"Alice"
Input{"user":{"id":123,"active":true}}
Output123
Input{"items":["apple","banana"]}
Output"banana"
🧠

How to Think About It

To read JSON in Bash, you use the jq tool which parses JSON and lets you select parts using simple expressions like .key. You run jq with the JSON file and the key path you want to extract.
📐

Algorithm

1
Get the JSON file path as input.
2
Use jq with the key or path you want to read from the JSON.
3
Print the extracted value to the console.
💻

Code

bash
#!/bin/bash

json_file='data.json'

# Read the 'name' field from JSON
name=$(jq '.name' "$json_file")
echo "Name: $name"
Output
Name: "Alice"
🔍

Dry Run

Let's trace reading the 'name' field from data.json containing {"name":"Alice"}.

1

Set JSON file path

json_file='data.json'

2

Run jq to extract 'name'

name=$(jq '.name' "data.json") # returns "Alice"

3

Print the result

echo "Name: $name" # outputs Name: "Alice"

StepCommandValue
1json_file='data.json'data.json
2jq '.name' data.json"Alice"
3echo "Name: $name"Name: "Alice"
💡

Why This Works

Step 1: jq parses JSON

The jq command reads the JSON file and extracts the value at the specified key path.

Step 2: Store output in variable

Using $(jq '.key' file) captures the extracted JSON value into a Bash variable.

Step 3: Print the value

Echoing the variable shows the JSON value, including quotes if it is a string.

🔄

Alternative Approaches

Using jq with raw output option
bash
#!/bin/bash
json_file='data.json'
name=$(jq -r '.name' "$json_file")
echo "Name: $name"
The <code>-r</code> option removes quotes from string output, making it easier to use in scripts.
Using jq to read nested JSON keys
bash
#!/bin/bash
json_file='data.json'
id=$(jq '.user.id' "$json_file")
echo "User ID: $id"
You can access nested keys by chaining them with dots, like <code>.user.id</code>.

Complexity: O(n) time, O(n) space

Time Complexity

jq reads the entire JSON file once, so time grows linearly with JSON size.

Space Complexity

jq loads the JSON into memory, so space usage grows with JSON size.

Which Approach is Fastest?

Using jq with raw output is fastest for string extraction; alternatives like parsing with other tools are slower or less reliable.

ApproachTimeSpaceBest For
jq basicO(n)O(n)Simple JSON extraction
jq with -rO(n)O(n)Clean string output without quotes
Manual parsing (not recommended)O(n)O(1)Very simple JSON but error-prone
💡
Use jq -r to get raw strings without quotes for easier Bash handling.
⚠️
Forgetting to quote the JSON file path or jq expression can cause errors or unexpected results.