Bash-jq-examples
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")
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
- TBH, this one feels like simply abusing jq until it pukes up what you asked 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"
Filter for two values in JSON
This has externalHostname at the beginning of the index, and then upTime maps down to the index under property which is a name: value pair
cat /tmp/foo | jq '.[] | {externalHostName, upTime: (.tags.property[] | select(.name == "up.time").value)}'
{
"externalHostName": "server01.fqdn.com",
"upTime": "54 minutes 37 seconds"
}
{
"externalHostName": "server02.fqdn.com",
"upTime": "5 days 19 hours 59 minutes 9 seconds"
}