Skip to content

Instantly share code, notes, and snippets.

@nathansgreen
Last active October 26, 2018 16:10
Show Gist options
  • Select an option

  • Save nathansgreen/d2483e7e78eab98979c25f4694a231eb to your computer and use it in GitHub Desktop.

Select an option

Save nathansgreen/d2483e7e78eab98979c25f4694a231eb to your computer and use it in GitHub Desktop.
Stuff I've had to do with jq

Simple things to do using jq

# turn a delimted string into an array:
echo '"2368;3924"' | jq 'split(";")
[
  "2368",
  "3924"
]
# turn array elements into numbers:
echo '["2368","3924"]' | jq 'map_values(.|tonumber)'

A one-liner of both: echo '"2368;3924"' | jq 'split(";")|map_values(.|tonumber)'

Output array of strings as unquoted lines:

echo '["a","b"]["c"]' |jq -r '.[]'
a
b
c

Something a bit more complicated

Here we filter based on multiple object property restrictions, then output array values. The select((.arr|length)>0) element is critical to avoid passing null farther down the stream.

echo '[
  {
    "a": true,
    "b": "good",
    "arr": ["v1", "v2"]
  },
  { "a": false,
    "b": "good",
    "arr": ["v3", "v4"]
  },
  { "a": true,
    "b": "bad",
    "arr": ["v5", "v6"]
  },
  { "a": true,
    "b": "good"
  }
]' |jq -r '.[]|select((.arr|length)>0 and .b=="good" and .a)|.arr|.[]'
v1
v2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment