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

JQ only return matching child results with parent

I am trying to get JSON data where a child key match exists, but I want to exclude data from other child elements that don’t match. An example would use the following JSON, trying to return id from the parent and quantity from the child, where the child catalog_object_id "VJXWCBDL":

[
  {
    "id": "a",
    "line_items": [
      {
        "catalog_object_id": "IKF7HPIP",
        "quantity": "5"
      },
      {
        "catalog_object_id": "VJXWCBDL",
        "quantity": "1"
      }
    ]
  },
  {
    "id": "b",
    "line_items": [
      {
        "catalog_object_id": "JXOACUE",
        "quantity": "4"
      }
    ]
  },
  {
    "id": "c",
    "line_items": [
      {
        "catalog_object_id": "VJXWCBDL",
        "quantity": "2"
      },
      {
        "catalog_object_id": "RGQMKXKL",
        "quantity": "3"
      }
    ]
  },
  {
    "id": "d",
    "line_items": [
      {
        "catalog_object_id": "VJXWCBDL",
        "quantity": "4"
      }
    ]
  }
]

The output that I’m looking for is:

[
  "a",
  "1"
]
[
  "c",
  "2"
]
[
  "d",
  "4"
]

When I use select based on the object id, it returns the values for the other ids as well. I’m sure there’s an easy answer to this that I haven’t been able to figure out.

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

jq '.[] | select ( .line_items[].catalog_object_id == "VJXWCBDL" ) | [ .id, .line_items[].quantity ]' test.json

What should I be doing instead?

>Solution :

Try

jq --arg q "VJXWCBDL" '
  .[] | [.id] + (.line_items[] | select(.catalog_object_id == $q) | [.quantity])
' test.json
[
  "a",
  "1"
]
[
  "c",
  "2"
]
[
  "d",
  "4"
]

Demo

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