Skip to content

Instantly share code, notes, and snippets.

@olih
Last active June 7, 2023 19:39
Embed
What would you like to do?
jq Cheet Sheet

Processing JSON using jq

jq is useful to slice, filter, map and transform structured json data.

Installing jq

On Mac OS

brew install jq

On AWS Linux

Not available as yum install on our current AMI. It should be on the latest AMI though: https://aws.amazon.com/amazon-linux-ami/2015.09-release-notes/

Installing from the source proved to be tricky.

Useful arguments

When running jq, the following arguments may become handy:

Argument Description
--version Output the jq version and exit with zero.
--sort-keys Output the fields of each object with the keys in sorted order.

Basic concepts

The syntax for jq is pretty coherent:

Syntax Description
, Filters separated by a comma will produce multiple independent outputs
? Will ignores error if the type is unexpected
[] Array construction
{} Object construction
+ Concatenate or Add
- Difference of sets or Substract
length Size of selected element
| Pipes are used to chain commands in a similar fashion than bash

Dealing with json objects

Description Command
Display all keys jq 'keys'
Adds + 1 to all items jq 'map_values(.+1)'
Delete a key jq 'del(.foo)'
Convert an object to array to_entries | map([.key, .value])

Dealing with fields

Description Command
Concatenate two fields fieldNew=.field1+' '+.field2

Dealing with json arrays

Slicing and Filtering

Description Command
All jq .[]
First jq '.[0]'
Range jq '.[2:4]'
First 3 jq '.[:3]'
Last 2 jq '.[-2:]'
Before Last jq '.[-2]'
Select array of int by value jq 'map(select(. >= 2))'
Select array of objects by value ** jq '.[] | select(.id == "second")'**
Select by type ** jq '.[] | numbers' ** with type been arrays, objects, iterables, booleans, numbers, normals, finites, strings, nulls, values, scalars

Mapping and Transforming

Description Command
Add + 1 to all items jq 'map(.+1)'
Delete 2 items jq 'del(.[1, 2])'
Concatenate arrays jq 'add'
Flatten an array jq 'flatten'
Create a range of numbers jq '[range(2;4)]'
Display the type of each item jq 'map(type)'
Sort an array of basic type jq 'sort'
Sort an array of objects jq 'sort_by(.foo)'
Group by a key - opposite to flatten jq 'group_by(.foo)'
Minimun value of an array jq 'min' .See also min, max, min_by(path_exp), max_by(path_exp)
Remove duplicates jq 'unique' or jq 'unique_by(.foo)' or jq 'unique_by(length)'
Reverse an array jq 'reverse'
@jsmucr
Copy link

jsmucr commented Jun 10, 2022

@ksemele How about this? :-)

map([.Key,.Value] | join(", ")) | .[]

@fearphage
Copy link

jq --raw-output '.[] | "\(.Key | gsub("^{ | }$"; "")), \(.Value | gsub("^{ | }$"; ""))"'

@mirisu2
Copy link

mirisu2 commented Jul 15, 2022

Hi,
I have an object and I would like to select from input_chunks all object where status.mem_size != "0b"
I tried like this .[] | select(.status.mem_size!="0b") or .input_chunks | select(.status.mem_size!="0b") but it didn't work :(
Maybe someone can help me?

{
  "storage_layer": {
    "chunks": {
      "total_chunks": 28,
      "mem_chunks": 27,
      "fs_chunks": 1,
      "fs_chunks_up": 0,
      "fs_chunks_down": 1
    }
  },
  "input_chunks": {
    "kube": {
      "status": {
        "overlimit": false,
        "mem_size": "0b",
        "mem_limit": "28.6M"
      },
      "chunks": {
        "total": 0,
        "up": 0,
        "down": 0,
        "busy": 0,
        "busy_size": "0b"
      }
    },
    "storage_backlog.1": {
      "status": {
        "overlimit": false,
        "mem_size": "0b",
        "mem_limit": "0b"
      },
      "chunks": {
        "total": 0,
        "up": 0,
        "down": 0,
        "busy": 0,
        "busy_size": "0b"
      }
    },
    "emitter_for_detect-nginx-ingress": {
      "status": {
        "overlimit": false,
        "mem_size": "0b",
        "mem_limit": "9.5M"
      },
      "chunks": {
        "total": 0,
        "up": 0,
        "down": 0,
        "busy": 0,
        "busy_size": "0b"
      }
    },
    "emitter_for_detect-aaaa-logger": {
      "status": {
        "overlimit": false,
        "mem_size": "3.0M",
        "mem_limit": "9.5M"
      },
      "chunks": {
        "total": 23,
        "up": 23,
        "down": 0,
        "busy": 23,
        "busy_size": "3.0M"
      }
    },
    "emitter_for_detect-kong-proxy-logger": {
      "status": {
        "overlimit": false,
        "mem_size": "99.6K",
        "mem_limit": "9.5M"
      },
      "chunks": {
        "total": 4,
        "up": 4,
        "down": 0,
        "busy": 4,
        "busy_size": "99.6K"
      }
    },
    "emitter_for_detect-elastic-logs": {
      "status": {
        "overlimit": false,
        "mem_size": "0b",
        "mem_limit": "9.5M"
      },
      "chunks": {
        "total": 0,
        "up": 0,
        "down": 0,
        "busy": 0,
        "busy_size": "0b"
      }
    },
    "emitter_for_detect-audit-logs": {
      "status": {
        "overlimit": false,
        "mem_size": "0b",
        "mem_limit": "9.5M"
      },
      "chunks": {
        "total": 0,
        "up": 0,
        "down": 0,
        "busy": 0,
        "busy_size": "0b"
      }
    },
    "emitter_for_detect-other": {
      "status": {
        "overlimit": false,
        "mem_size": "0b",
        "mem_limit": "9.5M"
      },
      "chunks": {
        "total": 0,
        "up": 0,
        "down": 0,
        "busy": 0,
        "busy_size": "0b"
      }
    }
  }
}

@jsmucr
Copy link

jsmucr commented Jul 16, 2022

.input_chunks | to_entries | map(.value | select(.status.mem_size != "0b") | .chunks)

@mirisu2
Copy link

mirisu2 commented Jul 16, 2022

.input_chunks | to_entries | map(.value | select(.status.mem_size != "0b") | .chunks)

what if I would like to have keys emitter_for_detect... for everyone where mem_size != "0b" ?

@jsmucr
Copy link

jsmucr commented Jul 16, 2022

@mirisu2 I'm not sure if I understand the question but maybe this...? :)

.input_chunks | to_entries | map(select(.key | startswith("emitter_for_detect")) | select(.value.status | .mem_size != "0b")) | from_entries
{
  "emitter_for_detect-aaaa-logger": {
    "status": {
      "overlimit": false,
      "mem_size": "3.0M",
      "mem_limit": "9.5M"
    },
    "chunks": {
      "total": 23,
      "up": 23,
      "down": 0,
      "busy": 23,
      "busy_size": "3.0M"
    }
  },
  "emitter_for_detect-kong-proxy-logger": {
    "status": {
      "overlimit": false,
      "mem_size": "99.6K",
      "mem_limit": "9.5M"
    },
    "chunks": {
      "total": 4,
      "up": 4,
      "down": 0,
      "busy": 4,
      "busy_size": "99.6K"
    }
  }
}

@mirisu2
Copy link

mirisu2 commented Jul 16, 2022

Yes. You got it right!
But I got {}

@jsmucr
Copy link

jsmucr commented Jul 17, 2022

Maybe old jq version? Try https://jqplay.org/.

@mirisu2
Copy link

mirisu2 commented Jul 17, 2022

I already tried on jqplay. The result is the same. :(

@jsmucr
Copy link

jsmucr commented Jul 17, 2022

@notorand-it
Copy link

notorand-it commented Oct 26, 2022

Puzzle: how do I go from this:

{
  "widgets": [
    {
      "name": "foo",
      "properties": [
        "baz"
      ]
    },
    {
      "name": "bar"
    }
  ]
}

to this

{
  "widgets": [
    {
      "name": "foo",
      "properties": [
        "baz",
        "boo"
      ]
    },
    {
      "name": "bar"
    }
  ]
}

Or, is it possible to I add an item into an internal array?

@jsmucr
Copy link

jsmucr commented Oct 31, 2022

@notorand-it Try this:

. as $root |
($root.widgets[] | select(.name != "foo")) as $others |
($root.widgets[] | select(.name == "foo") * { properties: (.properties + ["boo"])}) as $newfoo |
$root * { widgets: ([$newfoo] + [$others]) }

I'm pretty sure it can be done some more sophisticated way, but this works too and is easy to understand.

@twosider
Copy link

twosider commented Apr 13, 2023

Puzzle: how do I go from this:

{ "widgets": [ ...
  "properties":["baz"]
  ...

to this

{ "widgets": [...
   "properties": ["baz","boo"]
...

Or, is it possible to I add an item into an internal array?

This is a good one to understand how jq can manipulate an object directly:

jq '.widgets[0].properties += ["boo"]'

This works because adding an array to another array concatenates the elements:

jq -cn '[1]+[2]'
[1,2]
jq -cn '["baz"]+["boo"]'
["baz","boo"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment