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 do i use try catch in multiple sets of arrays in jq?

json example:

{
  "data": {
    "sub1": [
      {
        "sub2": {
          "sub3": 32,
          "steps": []
        }
      },
      {
        "sub2": {
          "sub3": 21,
          "steps": [
            {
              "task": [
                {
                  "active": 223,
                  "activel": 21
                }
              ]
            }
          ]
        }
      },
      {
        "sub2": {
          "sub3": 234,
          "steps": [
            {
              "task": [
                {
                  "active": 23,
                  "activel": 2
                }
              ]
            }
          ]
        }
      },
      {
        "sub2": {
          "sub3": 32,
          "steps": [
            {
              "task": []
            }
          ]
        }
      }
    ]
  }
}

what i have tried:

.data.sub1[]| [try(.sub2.steps[].task[].active) catch "error"]

in jqplay : https://jqplay.org/s/U2mWmdkhsm5

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

this is the closest i have gotten, but what i need is for it to write error for each part of the array where active doesnt exist.
like this:

"error"
223
23
"error"

this seems like a simple question, but i just cant figure out how to get this to work, so thanks in advance for any answers.

>Solution :

You can use the alternative operator //:

.data.sub1[] | .sub2.steps[].task[].active // "error"

See playground.

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