yi1
yi1

Reputation: 413

How do I mix jq operators?

I'm using jq to analyze JSON content via bash. Works well so far.

Now, I have this content:

{ "_id" : { "$oid" : "55a3fb74e4b0feb11ba5bec2" }, 
"alertId" : 15, "headline" : "License for XXXXXX is about to expire", 
"includedItems" : []}

Now I use jq easily to get the alertId and headline, like so:

jq .alertId,.headline FILENAME

But, I also want to add a count of items in the includedItems array. Like so:

jq '.includedItems | length' FILENAME

This work, but I need it all part of one command. The reason is that FILENAME is a file with a huge amount of JSON and if I were to run the commands separately, I'd spend a lot of time trying to thread the outputs together. So instead, I was hoping to find a way to achieve something like this:

jq .alertId,.headline,'.includedItems | length' FILENAME

But that doesn't work.

Upvotes: 1

Views: 288

Answers (1)

ruakh
ruakh

Reputation: 183504

The problem with '.alertId,.headline,.includedItems | length' is that , has higher precedence than |, so it's equivalent to '(.alertId,.headline,.includedItems) | length'. Since you want your | to have higher precedence — you want .includedItems | length to be just a single list-item — you need to group it with parentheses:

jq '.alertId, .headline, (.includedItems | length)' FILENAME

Upvotes: 2

Related Questions