How to check if element exists in array with jq

前端 未结 5 809
悲哀的现实
悲哀的现实 2020-12-08 14:53

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:

{
    \"fr         


        
5条回答
  •  无人及你
    2020-12-08 15:06

    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" )
    

    IN/1

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

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

    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;
    

提交回复
热议问题