0

I am writing a shell script that will read from a text file line by line some item names stored in the $entry variable within a while loop. With a curl command, I retrieve a json which is given as sample json response. I need to be able to compare the input text value which is saved in $entry to all the values within the item_name array and return true/false depending on if the $entry value is present using jq library. I am able to retrieve the item names values using the jq command written below, but I am not familiar how to compare with the input string. when I use "select" command to compare, I get syntax error. I am quite new to jq and not proficient with using filters/select statement for comparison, any pointers on how to resolve it?

bash variable

$entry = "some value from a text file"

sample json response

"response": {
    "numFound": 2,
    "docs": [{
            "country": "USA",
            "item_name": [
                "parachutes",
                "air balloon"
            ]
        },
        {
            "country": "Brazil",
            "item_name": [
                "gliders",
                "aircraft carriers"
            ]
        }
    ]
}

jq command

echo "$RESPONSE" | jq '.' | jq '.["response"]["docs"]' | jq '.[].item_name' | jq - r '.[]'

Update:

The jq command that works as expected is

echo $RESPONSE | jq -e '.' | jq -r '.["response"]["docs"] | .[].item_name ' | jq -s 'add' | jq 'any(. == "'"$entry"'") | if . == true then "Exact match" else "No Exact match" end'
neelmeg
  • 2,459
  • 6
  • 34
  • 46
  • Export `entry` to the environment, and then `env.entry` refers to it in jq. Is there anything else you need to know before you can solve this problem yourself? (Since you already found Q&A entries showing how to compare to a static value, passing in a variable is the only change needed to convert code that compares to a static value to instead compare to a variable). – Charles Duffy Sep 02 '22 at 17:49
  • BTW, there's no reason to pipe a bunch of separate copies of jq together; it's much more efficient to write your jq code to use pipes _inside_ one copy of jq. That is, `jq -r 'a | b | c'` instead of `jq 'a' | jq 'b' | jq -r 'c'` – Charles Duffy Sep 02 '22 at 17:51

0 Answers0