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

Time:09-29

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.

CodePudding user response:

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.

  • Related