JSON JQ 如果没有其他 [英] JSON JQ if without else

查看:28
本文介绍了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 是强制性的.我不想在 else 块内做任何事情.无论如何,我可以忽略 else 或只是在 else 中打印一些 whitespce.

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

附言我的猜测是,无论 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 without 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 .结束

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

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