如何使用jq检查数组中是否存在元素 [英] How to check if element exists in array with jq

查看:54
本文介绍了如何使用jq检查数组中是否存在元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,我需要检查该数组中是否存在元素或使用jq,fruit.json:

I have an array and I need to check if elements exists in that array or to get that element from the array using jq, fruit.json:

{
    "fruit": [
        "apple", 
        "orange",
        "pomegranate",
        "apricot",
        "mango"
    ]
}


cat fruit.json | jq '.fruit .apple' 

不起作用

推荐答案

包含"的语义一点也不简单.一般来说,最好使用 'index' 来测试数组是否具有特定值,例如

The semantics of 'contains' is not straightforward at all. In general, it would be better to use 'index' to test if an array has a specific value, e.g.

.fruit | index( "orange" )

但是,如果感兴趣的项目本身是一个数组,则一般形式:

However, if the item of interest is itself an array, the general form:

 ARRAY | index( [ITEM] )

应该被使用,例如:

[1, [2], 3] | index( [[2]] )  #=> 1

IN/1

如果你的 jq 有 IN/1 那么更好的解决方案是使用它:

IN/1

If your jq has IN/1 then a better solution is to use it:

.fruit as $f | "orange" | IN($f[])

如果你的 jq 有 first/1(和 jq 1.5 一样),那么这里是 IN/1 的快速定义:

If your jq has first/1 (as does jq 1.5), then here is a fast definition of IN/1 to use:

def IN(s): first((s == .) // empty) // false;

any(_;_)

另一种有时更方便的有效替代方法是使用 any/2,例如

any(.fruit[]; . == "orange")

或等效地:

any(.fruit[] == "orange"; .)

这篇关于如何使用jq检查数组中是否存在元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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