使用jq选择具有与许多值之一匹配的键的JSON对象。

huangapple go评论49阅读模式
英文:

Select JSON objects with key matching one of many values using jq

问题

以下是您要翻译的内容:

"Let's say I have a few JSON objects in a Bash variable :

json='{"key":"100"}{"key":"200"}{"key":"300"}';

To select the object with key matching 100 I can do :

printf '%s\n' "$json" | jq 'select ( .key == "100" )';

As @axiac pointed out in the comments, I can use or to match one of several values.

printf '%s\n' "$json" | jq 'select(.key == "100" or .key == "200")

But what if I need to match key against a larger number of values, in which case using or becomes cumbersome?

What code would select all objects with key matching a value between 99 and 201?"

英文:

Let's say I have a few JSON objects in a Bash variable :

json='{"key":"100"}{"key":"200"}{"key":"300"}'

To select the object with key matching 100 I can do :

printf '%s\n' "$json" | jq 'select ( .key == "100" )'

As @axiac pointed out in the comments, I can use or to match one of several values.

printf '%s\n' "$json" | jq 'select(.key == "100" or .key == "200")

But what if I need to match key against a larger number of values, in which case using or becomes cumbersome?

What code would select all objects with key matching a value between 99 and 201?

答案1

得分: 1

> 选择所有键匹配值在99和201之间的对象?

将“between”解释为“严格在之间”的一种方式是:

    select(.key | tonumber | 99<. and .<201 )

> 匹配多个值中的一个

当可以将值指定为流时,也可以使用`IN/1`:

    select(.key | tonumber | IN(range(100;200)))


当然,在当前情况下,上述第一种解决方案(使用'<')将更高效。
英文:

> select all objects with key matching a value between 99 and 201?

Interpreting "between" as "strictly between", one way would be:

 select(.key | tonumber | 99&lt;. and .&lt;201 )

> to match one of several values

When it's possible to specify the values as a stream, one can also use IN/1:

 select(.key | tonumber | IN(range(100;200)))

Of course in the present case, the first solution above (using '<') would be more efficient.

答案2

得分: 0

Sure, here's the translation of the code part:

printf '%s\n' "$json" | jq 'select((.key|tonumber >=100) and (.key|tonumber <=200))'

英文:
printf &#39;%s\n&#39; &quot;$json&quot; |jq &#39;select((.key|tonumber &gt;=100) and (.key|tonumber &lt;=200))&#39;

huangapple
  • 本文由 发表于 2023年5月6日 18:57:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76188487.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定