Skip to content

Instantly share code, notes, and snippets.

@pavelfomin
Last active June 14, 2024 19:51
Show Gist options
  • Save pavelfomin/0633856e66a985d82f091cf27ab30ba7 to your computer and use it in GitHub Desktop.
Save pavelfomin/0633856e66a985d82f091cf27ab30ba7 to your computer and use it in GitHub Desktop.
JQ usage examples
{
"contracts": [
{
"name": "Honda001",
"manufacturer": {
"name": "Honda"
}
},
{
"name": "Toyota001",
"manufacturer": {
"name": "Toyota"
}
},
{
"name": "Honda001",
"manufacturer": {
"name": "Honda"
}
},
{
"name": "Lexus001",
"manufacturer": {
"name": "Lexus"
}
},
{
"name": "Nissan001",
"manufacturer": {
"name": "Nissan"
}
},
{
"name": "Toyota002",
"manufacturer": {
"name": "Toyota"
}
}
]
}

Transformation

Number of contract

jq '.contracts | length' contracts-test.json

Contract names

jq '.contracts | .[].name' contracts-test.json

Number of unique manufacturers

jq '.contracts | map(.manufacturer) | unique_by(.name) | length' contracts-test.json

Unique manufacturer names

jq '.contracts | map(.manufacturer) | unique_by(.name) | .[].name' contracts-test.json

works but breaks json into separate inputs

jq -c '.contracts[] | {m: .manufacturer.name, c: .name}' contracts-test.json
jq '.contracts[] | select(.manufacturer.name == "Honda")'  contracts-test.json

List manufacturers and their contracts

jq '.contracts | group_by(.manufacturer.name) | map({"manufacturer": .[0].manufacturer.name, "contracts": map(.name)})' contracts-test.json

See working example at https://jqplay.org/s/n3i9BZwgE0_m

Create new JSON

Using shell parameter passed

compatibility="forward"
jq -n --arg content "$compatibility" '{"compatibility": $content}'

Escape schema json parameter as string

jq -n --arg content "$schema" --arg artifact "$filename" \
'{"schema": $content, "metadata": {"properties": {"artifact": $artifact} } }'

Include json unescaped passed as a parameter

jq -n --argjson data $vault_data '{"data": $data}'
{
"type": "message",
"attachments": [
{
"contentType": "application/vnd.microsoft.card.adaptive",
"content": {
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.2",
"body": [
{
"type": "TextBlock",
"text": "{{ message }}",
"weight": "bolder",
"size": "large",
"wrap": true,
"color": "{{ color }}"
}
],
"msteams": {
"width": "Full"
}
}
}
]
}

Replace values in JSON tempate and post MS Teams notification

status="good"
message="Test message"
json=$(jq --arg status "$status" --arg message "$message" \
          '.attachments[0].content.body[0].text = $message | .attachments[0].content.body[0].color = $status' \
          .github/teams.json)
curl -s --show-error --fail --request POST --header 'Content-Type: application/json;charset=UTF-8' --data "$json" $teams_hook_url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment