How to check if element exists in array with jq

前端 未结 5 810
悲哀的现实
悲哀的现实 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:58

    If you're open to using something other than jq, then I can highly recommend Xidel.
    With it you can combine JSONiq and XPath/XQuery to process JSON!

    To have it simply return a boolean:

    $ xidel -s fruit.json -e '$json/contains((fruit)(),"apple")'
    true
    

    To have it return the element if the array fruit contains "apple":

    $ xidel -s fruit.json -e '$json/(fruit)()[contains(.,"apple")]'
    apple
    

    Above is "XPath notation". "Dot notation" (like jq):

    $ xidel -s fruit.json -e '($json).fruit()[contains(.,"apple")]'
    apple
    

提交回复
热议问题