JSON JQ if without others

I use the following JQ command to filter JSON. My requirement is to filter out the JSON message if the expected node is present. Or, do nothing. Therefore, I use if, elif, ....

sed -n "s/.*Service - //p" $1/response.log* | jq "if (.requests | length) != 0 then .requests |= map(select(.id == \"123\")) elif (.result | length ) != 0 then .result |= map(select(.id== \"123\")) else " " end" > ~/result.log 

It seems like a must here. I do not want to do anything inside the else block. Anyway, I can ignore others or just print some whitespce inside else.

In the above case, it prints double quotation marks "" in the result file.

+17
source share
2 answers

You can use the idiom:

 if CONDITION then WHATEVER else empty end 

empty is a filter that displays nothing at all - even zero, which, after all, is something (namely, the JSON value). This is a bit like a black hole, only blacker - it will absorb everything that it has proposed, but unlike a black hole, it does not even emit Hawking radiation.

In your case, you have "elif", so using "else empty" is probably what you need, but for reference, the above is exactly equivalent:

 select(CONDITION) | WHATEVER 

PS I assume that whatever the purpose of the sed command is, it can be done more reliably as part of the jq program, possibly using walk/1 .

UPDATE

After the release of jq 1.6, a change was made, so that "if without the other" has the semantics of "if _, then _ else. End", that is:

if P then Q end === if P then Q else. end if P then Q else. end if P then Q else. end if P then Q else. end

+31
source

Since you are not making any further changes to the object, simply use the "identity" filter . .

 if (.requests | length) then ... else . end 

On the other hand, you simply update the requests or result property, if not empty, using map . Verification is not required. If it is empty, then it will be empty.

You can simplify your filter:

 .requests |= map(select(.id == \"123\")) | .result |= map(select(.id== \"123\")) 
+2
source

Source: https://habr.com/ru/post/986244/


All Articles