Monday, 20 December 2021

JQ and output control and searching ... I must remember this

As per many many previous posts, I'm continuing to learn - and love - jq.

One thing that's especially useful is the ability to be able to corral multiple facets together using the pipe ( | ) symbol, especially when searching/listing.

I did, however, fall into a trap this AM.

So I'm querying my IBM Cloud account for a Key Protect instance: -

ic resource service-instances --output JSON | jq -r '.[] | {Name: .name} | select(.name | endswith("kms"))'

which resulted in: -

jq: error (at <stdin>:77): endswith() requires string inputs

So what did I do wrong ?

To break it down, this is what I'm doing: -

List my IBM Cloud Service Instances

ic resource service-instances

Print the output in JavaScript Object Notation (JSON)

ic resource service-instances --output JSON

Parse the output via jq

ic resource service-instances --output JSON | jq

Strip out double-quotes where possible ( i.e. raw text )

ic resource service-instances --output JSON | jq -r

Inspect the array that comprises the output

ic resource service-instances --output JSON | jq -r

Only print the name field, aka .name, *AND* format it as Name

ic resource service-instances --output JSON | jq -r '.[] | {Name: .name}

Use the name field for a select ( search )

ic resource service-instances --output JSON | jq -r '.[] | {Name: .name} | select(.name

Look at the end of the name field, for the characters "kms" - short for Key Management System

ic resource service-instances --output JSON | jq -r '.[] | {Name: .name} | select(.name | endswith("kms"))'

and that's where the borkage occur...

Can you see what I did wrong ?

I asked jq to format the output of the .name field as Name, and then tried to search the output for .name ....

In this case, jq is reformatting the output JSON from .name to .Name ...

Here's an example with the search removed: -

ic resource service-instances --output JSON | jq -r '.[] | {Name: .name}'

{
  "Name": "davehay-1638264407-kms"
}
{
  "Name": "davehay-1638264407-state"
}

Once I changed my search: -

ic resource service-instances --output JSON | jq -r '.[] | {Name: .name} | select(.Name | endswith("kms"))'

{
  "Name": "davehay-1638264407-kms"
}

I'm good to go ....

No comments:

Today I Learned - useful keyboard shortcut for macOS

Last night, I chose to charge my Apple Magic Mouse - which, you might say, seems like a reasonable thing to do. The thing is that, anyone wh...