Bash-jq-examples

From I Will Fear No Evil
Revision as of 11:28, 19 April 2024 by Chubbard (talk | contribs)
Jump to navigation Jump to search

Some examples of using jq to do filtering..

raw jason:
{
  "1": [
    {
      "id": "123456789",
      "accountId": "a1-supplies-01234",
      "accountName": "a1-supplies",
      "status": "LIVE",
      "customerId": "A1 Supplies",
      "customerType": "display"
    }
  ]
}
Map will iterate through the array(s) looking for key status, and value LIVE
<json here> | jq  -c 'map(select(.[].status | contains ("LIVE")))' | jq
  • Running the output through jq again puts the line breaks back in place
  • contains in a search DOES honor pipes
 contains ("LIVE"|"DEAD") 

Stackoverflow details

Return the array where a value matches

cat /tmp/APP_JSON  | jq '.system_env_json.someService.[].[] | select (.name == "foobar")'
{
  "label": "generic-name",
  "name": "foobar",
  "tags": [],
  "instance_guid": "64fcbaba-3684-4435-b50a-adaa7fc9c2",
  "instance_name": "foobar",
  "binding_guid": "5e4c8-6c7-420-9f18f-8f8df52",
  "binding_name": null,
  "credentials": {
    "apitoken": "some token",
    "apiurl": "https://api.iwillfearnoevil.com/e/82542d-4820-8b5-e032dbc66/api",
    "environmentid": "something"
  },
  "syslog_drain_url": "",
  "volume_mounts": []
}

Another way to filter down to what you are searching for

JSON_FILE=$1

jq ' .system_env_json.someService | paths(select(. != null and type == "object" and has("credential-type"))) as $p |
    {
        name: getpath($p[:-1] + ["name"]),
        path: $p | join("."),
        credentials: getpath($p)
    }' < "$JSON_FILE"