json and jq

dos2unix

Well-Known Member
Joined
May 3, 2019
Messages
4,408
Reaction score
4,601
Credits
41,638
Linux.org is an interesting site. We have some pro's on here (you know who you are, and I do too).
But it seems the vast majority are hobbyists, nothing wrong with that, in fact it's what makes Linux work.

But some of my articles are most for people who deal enterprise applications, so if you don't use the tools
the article isn't really that helpful, this is one such article :-) How many of you deal with json everyday?
Unfortunately I have to use it lot (not always by choice). I'm not great with reading json, so I cheat.

Here is a sample json file. You can name it sample.json
Code:
{
  "users": [
    {"name": "alice", "age": 30, "role": "admin", "active": true},
    {"name": "bob", "age": 25, "role": "dev", "active": false},
    {"name": "charlie", "age": 35, "role": "dev", "active": true}
  ],
  "metadata": {
    "total": 3,
    "generated": "2025-01-01"
  }
}

This one is pretty small, and I don't have deep nested data. But imagine dozens of names, and dozens of nested arrays.
How can we make it more readable? Tah duh.. "jq".

Basic extraction
Code:
# Pretty print (the gateway drug)
cat sample.json | jq '.'

# Get all usernames
jq '.users[].name' sample.json

# Get first user
jq '.users[0]' sample.json

# Get metadata field
jq '.metadata.generated' sample.json

Basic filtering
Code:
# Active users only
jq '.users[] | select(.active == true)' sample.json

# Devs only
jq '.users[] | select(.role == "dev")' sample.json

# Age over 28
jq '.users[] | select(.age > 28) | .name' sample.json

Transforming the data
Code:
# Just names as array
jq '[.users[].name]' sample.json

# Build new objects
jq '.users[] | {username: .name, is_admin: (.role == "admin")}' sample.json

# Count users
jq '.users | length' sample.json

Some real world examples
Code:
# EC2 instances
aws ec2 describe-instances | jq '.Reservations[].Instances[] | {id: .InstanceId, state: .State.Name}'

# Podman/Docker
podman ps --format json | jq '.[].Names'

Wanna impress your json dev? The power move :-)
Code:
# CSV output
jq -r '.users[] | [.name, .age, .role] | @csv' sample.json

"I don't read JSON. I jq it."
 




Follow Linux.org

Members online


Top