How to check if element exists in array with jq

前端 未结 5 802
悲哀的现实
悲哀的现实 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 14:55

    To have jq return success if the array fruit contains "apple", and error otherwise:

    jq -e '.fruit[]|select(. == "apple")' fruit.json >/dev/null
    

    To output the element(s) found, omit >/dev/null. If searching for a fixed string, this isn't very relevant, but it might be if the select expression might match different values, e.g. if it's a regexp.

    To output only distinct values, pass the results to unique.

    jq '[.fruit[]|select(match("^app"))]|unique' fruit.json
    

    will search for all fruits starting with app, and output unique values. (Note that the original expression had to be wrapped in [] in order to be passed to unique.)

提交回复
热议问题