1

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow! I didn't know about the .[0:100] substring notation yet. And I had no idea that it's as simple as [] |=. Thank you! You just saved my sanity after I spent 2 hours on this!
@peak The text that says "10 characters" is about the jqplay example. The question asks how to truncate the error messages to 100 characters but the example JSON does not contain error messages that large.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.