Skip to content

Instantly share code, notes, and snippets.

@ohmydevops
Last active November 17, 2023 05:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohmydevops/6f07c8e982e8e2d910c6ce051ce2a6ff to your computer and use it in GitHub Desktop.
Save ohmydevops/6f07c8e982e8e2d910c6ce051ce2a6ff to your computer and use it in GitHub Desktop.
Mashhad LUG 268
{
"users": [
{
"id": 1,
"name": "Alice",
"age": 28,
"status": "active",
"books": [
"Test",
"Good",
"Bad"
]
},
{
"id": 2,
"name": "Charlie",
"age": 35,
"status": "inactive"
},
{
"id": 3,
"name": "Bob",
"age": 22,
"status": "active"
}
],
"settings": {
"theme": "light",
"notifications": true
},
"metadata": [
{
"version": "1.0",
"last_updated": "2023-01-01"
},
{
"version": "2.0",
"last_updated": "2024-02-01"
}
]
}
#!/usr/bin/env bash
# Download this two files and then: chmod +x jq.sh
### Define the path to the JSON file
json_file="data.json"
### Read normally
cat $json_file
### Read json data
cat $json_file | jq
jq '' $json_file
# Read a specific part of json data
jq '.metadata' $json_file
jq '.metadata[]' $json_file
jq '.users[2].name' $json_file
jq '.users[0].books[1]' $json_file
jq '.users[0].books' $json_file
jq '.users[0].books[]' $json_file
# Sort data
jq '.users | sort_by(.name)' $json_file
jq '.users | sort_by(.age)' $json_file
jq '.users | sort_by(.age) | reverse' $json_file
# Filter json data
jq '.users[] | select(.age > 30)' $json_file
jq '.users | map(select(.age > 25)) | sort_by(.age)' $json_file
jq '.metadata[] | select(.version == "2.0")' $json_file
# Map on json data
jq '.users | map(.age *= 2) | sort_by(.age) | reverse' $json_file
jq '.users | map(.age * 2)' $json_file
# Update data
jq '.users[0].age = 30 | .users[1].age = 22' $json_file > clean_data.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment