Noelle.dev

jq Cheat Sheet

How to perform common operations on JSON documents.

jq is a very useful tool for parsing and manipulating JSON documents on the command line. For a comprehensive reference on all the features, see the jq manual.

The following examples will use this document as input:

{
  "name": "Julia Sommers",
  "items": ["car", "horse", "laptop"],
  "friends": [
    { "name": "Amanda Brush", "pet": "dog" },
    { "name": "January Stiles", "pet": "bird" },
    { "name": "Grace Rose", "pet": "bird" }
  ]
}

Identity

$ cat data.json | jq '.'
{
  "name": "Julia Sommers",
  "items": [
    "car",
    "horse",
    "laptop"
  ],
  "friends": [
    {
      "name": "Amanda Brush",
      "pet": "dog"
    },
    {
      "name": "January Stiles",
      "pet": "bird"
    },
    {
      "name": "Grace Rose",
      "pet": "bird"
    }
  ]
}

Get single value from document

$ cat data.json | jq '.name'
"Julia Sommers"

Get the first N items of an array

$ cat data.json | \
  jq '.items[:2]'
[
  "car",
  "horse"
]

Map an array

$ cat data.json | \
  jq '[.friends[] | .name]'
[
  "Amanda Brush",
  "January Stiles",
  "Grace Rose"
]

Filter an array

$ cat data.json | \
  jq '[.friends[] | select(.pet=="bird")]'
[
  {
    "name": "January Stiles",
    "pet": "bird"
  },
  {
    "name": "Grace Rose",
    "pet": "bird"
  }
]

Reduce an array

$ cat data.json | \
  jq 'reduce .items[] as $item (""; . + $item)'
"carhorselaptop"