Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get a key/value pair on a sibling object in a JSON array conditionally

I’m interacting with an API that returns an array of objects related to a product in JSON format:

[
  {
    "type": "category",
    "name": "food"
  },
  {
    "type": "category",
    "name": "fruit"
  },
  {
    "type": "barcode",
    "name": "123456"
  }
]

I’m trying to use jq tool on bash in the shortest and tidiest form, to check if a product has a barcode and it’s categorized as food. In other words, check if an object with type=barcode exists in the array, then check if there is an object with type=category together with name=food.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This outputs true or false based on your requirements:

any(.type=="barcode") and any(.type=="category" and .name=="food")

jq -e will set the exit code of the program accordingly:

if jq -e '...'; then
  ...
fi

Without -e:

if test "$(jq '...')" = true; then
  ...
fi

And not necessarily shorter or tidier, but semantically easier to follow:

group_by(.type)
| map({
    key: first.type,
    value: map(.name)
})
| from_entries
| .category as $cat
| .barcode and ("food"|IN($cat[]))

This first builds an intermediate object of the form:

{
  "barcode": [
    "123456"
  ],
  "category": [
    "food",
    "fruit"
  ]
}

Which you can then query, e.g. does it have a barcode and is "food" one of the categories.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading