otherguy
otherguy

Reputation: 995

Replace array values if they exist with jq

While I use jq a lot, I do so mostly for simpler tasks. This one has tied my brain into a knot.

I have some JSON output from unit tests which I need to modify. Specifically, I need to remove (or replace) an error value because the test framework generates output that is hundreds of lines long.

The JSON looks like this:

{
  "numFailedTestSuites": 1,
  "numFailedTests": 1,
  "numPassedTestSuites": 1,
  "numPassedTests": 1,
  ...
  "testResults": [
    {
      "assertionResults": [
        {
          "failureMessages": [
            "Error: error message here"
          ],
          "status": "failed",
          "title": "matches snapshot"
        },
        {
          "failureMessages": [
            "Error: another error message here",
            "Error: yet another error message here"
          ],
          "status": "failed",
          "title": "matches another snapshot"
        }
      ],
      "endTime": 1617720396223,
      "startTime": 1617720393320,
      "status": "failed",
      "summary": ""
    },
    {
      "assertionResults": [
        {
          "failureMessages": [],
          "status": "passed",
        },
        {
          "failureMessages": [],
          "status": "passed",
        }
      ]
    }
  ]
}

I want to replace each element in failureMessages with either a generic failed message or with a truncated version (let's say 100 characters) of itself.

The tricky part (for me) is that failureMessages is an array and can have 0-n values and I would need to modify all of them.

I know I can find non-empty arrays with select(.. | .failureMessages | length > 0) but that's as far as I got, because I don't need to actually select items, I need to replace them and get the full JSON back.

Upvotes: 1

Views: 2669

Answers (1)

axiac
axiac

Reputation: 72395

The simplest solution is:

.testResults[].assertionResults[].failureMessages[] |= .[0:100]

Check it online!

The online example keeps only the first 10 characters of the failure messages to show the effect on the sample JSON you posted in the question (it contains short error messages).

Read about array/string slice (.[a:b]) and update assignment (|=) in the JQ documentation.

Upvotes: 3

Related Questions