简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM