Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

if statement - JSON JQ if without else

I use the following JQ command to filter out the JSON. My requirement is to filter out the JSON message if the expected node is present. Or else, do nothing. Hence, 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

Looks like else is mandatory here. I dont want to do anything inside the else block. Is there anyway, I can ignore else or just print some whitespce inside else.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may want to use the idiom:

if CONDITION then WHATEVER else empty end

empty is a filter that outputs nothing at all -- not even null, which is after all something (namely a JSON value). It's a bit like a black hole, only blacker -- it will consume whatever it's offered, but unlike a black hole, it does not even emit Hawking radiation.

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

select(CONDITION) | WHATEVER

P.S. My guess is that whatever the goal of the sed command, it could be done more reliably as part of the jq program, perhaps using walk/1.

UPDATE

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...