JSON JQ(如果没有其他条件) [英] JSON JQ if without else

查看:73
本文介绍了JSON JQ(如果没有其他条件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下JQ命令来过滤JSON.我的要求是,如果存在预期的节点,则过滤掉JSON消息.否则,什么都不做.因此,我使用if,elif,....

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

在这里像其他一样是强制性的.我不想在else块内做任何事情.无论如何,我可以忽略其他内容,或者在其他内容中打印一些空白.

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.

推荐答案

您可能想使用以下成语:

You may want to use the idiom:

if CONDITION then WHATEVER else empty end

empty是一个根本不输出任何内容的过滤器-甚至不为null,这毕竟是某种东西(即JSON值).它有点像一个黑洞,只是更黑了-它会消耗掉所提供的任何东西,但是与黑洞不同,它甚至不会发出霍金辐射.

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.

在您的情况下,您有一个"elif",因此您可能需要使用"else empty",但作为参考,以上内容完全等同于:

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.我的猜测是,无论sed命令的目标是什么,它都可以作为jq程序的一部分更可靠地完成,也许可以使用walk/1来完成.

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.

在发布jq 1.6之后,进行了更改,以使"if if else else"的语义为"if _ then _ else.end",即:

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

这篇关于JSON JQ(如果没有其他条件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆