Skip to content

Instantly share code, notes, and snippets.

@kylelambert101
Last active September 23, 2022 15:06
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 kylelambert101/c09f9c8ce0c930faea055bdacdc659bd to your computer and use it in GitHub Desktop.
Save kylelambert101/c09f9c8ce0c930faea055bdacdc659bd to your computer and use it in GitHub Desktop.
Bash -> jq CheatSheet
# Aggregate keys of all objects in an array
jsonArrayData | jq '[.[] | keys] | flatten | unique'
# Map array to reduced objects and sort by a field
# Assumes array of {id, name, items:[]}
jsonArrayData | jq '[.[] | {id, name, itemCount:.items | length}] | sort_by(.itemCount)'
# Filter an array by matching property
jsonArrayData | jq '. [] | select(.id == "SomeId")'
# Property contains
jsonArrayData | jq '.[] | select(.name | contains("some string"))'
# Cast string to upper or lowercase
jsonArrayData | jq '.[] | select(.name | ascii_downcase | contains("lowercase string"))'
jsonArrayData | jq '.[] | select(.name | ascii_upcase | contains("UPPERCASE STRING"))'
# Convert array to object keyed on array[].id
jsonArrayData | jq 'map({(.id|tostring): .}) | add'
# Given this:
# [
# {
# "id": "Thing A",
# "thing": "stuff"
# },
# {
# "id": "Thing B",
# "thing": "stuff"
# }
# ]
#
# Yields this:
# {
# "Thing A": {
# "id": "Thing A",
# "thing": "stuff"
# },
# "Thing B": {
# "id": "Thing B",
# "thing": "stuff"
# }
# }
# Bring parent data into a flattened child array
# (Keep in mind that if parent and child have fields with the same name, parent fields may need to be mapped to unique names to avoid collision)
jsonArrayData | jq '[.[] | .childArray + del(.childArray)]'
# Given this:
# {
# parentId:123,
# children:[
# {
# name: "Child1"
# },
# {
# name: "Child2"
# }
# ]
# }
#
# Yields this:
# [
# {
# parentId: 123,
# name: "Child1"
# },
# {
# parentId: 123,
# name: "Child2"
# }
# ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment