英文:
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<. and .<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 '%s\n' "$json" |jq 'select((.key|tonumber >=100) and (.key|tonumber <=200))'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论