Home > Software engineering >  How filter json file with jq using bash
How filter json file with jq using bash

Time:02-15

I am trying to filter my json file using bash, which file could be something like:

{
    "key1": [],
    "key2":["first_value","second_value"]
}

In case I would like to fetch key1 and key2 I got I can do something like:

if $(cat $my_json | jq 'has("key1")'); then
  values=$(jq -r ".key1" "$my_json")

  for item in $values
  do
    echo "Item : $item"
  done
fi

The output of the previous is:

Output:

Item : []

This prevents any issues in the case my file hasn't such key and I want to verify that.

How can I verify that values is empty, referred to my example?
I want to avoid any iteration on empty values.
Is there any way to verify the existing key with jq, that should not be empty?

The goal I would like to achieve is something like redirected at the end of a file

key2:
- first_value
- second_value

in case of key, since it is empty I don't want to have any results

CodePudding user response:

One option might be using

jq '.| select( has("key1"))|to_entries[] | select( .value | length == 0 )' $my_json

Demo

Edit(after question's edit): If you need to get the values of the non-empty arrays unlike to the previous one, then just convert the above filter to

jq -r '.......| length > 0) | "\(.key):", "- \(.value[])"' $my_json

through use of string interpolation

Demo

CodePudding user response:

In jq you can use the length filter to get the size of an array.

$ echo '{"key1": [], "key2":["1","2"]}' | jq -r ".key2 | length"
2
$ echo '{"key1": [], "key2":["1","2"]}' | jq -r ".key1 | length"
0

Also, even with that you'll find a problem iterating the elements of the array stored in $values. I think that what you want is this:

values=$(jq -r ".key1[]" "$my_json")

CodePudding user response:

This discards all items with an empty array, and iterates over the rest printing out the key name, then all array items.

jq -r 'to_entries[] | select(.value | length > 0) | .key, "- \(.value[])"'
key2
- first_value
- second_value

Demo

  • Related