Using BASH and JQ I want to compare a json file against a bash array

Issue

Example:

BASH ARRAY
FRUITS=("apple" "banana" "orange")

fruit.json

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

What I need to do:

  1. Compare Bash fruit array against fruit.json file and output if it matches all the elements.
  2. If the fruit.json file is missing a fruit element from the bash array I have to display which one it is.
  3. If the fruit.json file has any extra fruit elements that are not in the bash array I have to output it.

I managed to figure out the first two tasks but I am having trouble with the third. Any ideas on how to achieve the third using bash and jq?

Solution

This response addresses the task for which help is requested:

If the fruit.json file has any extra fruit elements that are not in the bash array I have to output it.

The following will output the strings corresponding to those elements in .fruit that do not appear in the bash array, assuming the entries in both arrays are all the same typographical case:

comm -23 <(< fruit.json jq -r '.fruit | sort[]') <(printf '%s\n' "${FRUITS[@]}" | sort )

This uses the standard command-line utilities comm, sort, and printf. A "pure jq" solution would also be straightforward except perhaps for the importing of the elements of the bash array into jq.

If the typographical case is inconsistent, you could use ascii_downcase on the jq end, and tr A-Z a-z for the bash array elements.

Answered By – peak

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published