Omitting null values for sub() in JQ

Viewed 213

I'm trying to change # to %23 in every context value, but I'm having problem with null values.

The shortened JSON is:

{
  "stats": {
    "suites": 1
  },
  "results": [
    {
      "uuid": "676-a46b-47a1-a49f-4da4e46c1120",
      "title": "",
      "suites": [
        {
          "uuid": "gghjh-56a9-4713-b139-0d5b36bc7fbc",
          "title": "Login process",
          "tests": [
            {
              "pass": false,
              "fail": true,
              "pending": false,
              "context": "\"screenshots/login.spec.js/Login process -- should login #11 (failed).png\""
            },
            {
              "pass": false,
              "fail": false,
              "pending": true,
              "context": null
            }
          ]
        }
      ]
    }
  ]
}

And the JQ command I think it's closest to correct is:

jq '.results[].suites[].tests[].context | strings | sub("#";"%23")'

But the problem is that I need to get in return full edited file. How could I achieve that?

2 Answers

You were close. To retain the original structure, you need to use the update operator (|=) instead of pipe. Enclosing the entire expression to the left of it in parentheses is also necessary, otherwise the original input will be invisible to |=.

(.results[].suites[].tests[].context | strings) |= sub("#"; "%23")

Online demo

change # to %23 in every context value

You might wish to consider:

walk( if type=="object" and (.context|type)=="string"
      then .context |= gsub("#"; "%23")
      else . end )
Related