Home > Mobile >  Remove last character from json output using JQ
Remove last character from json output using JQ

Time:09-23

I have a json that looks like this:

{ 
  "HostedZones": [
      {
          "ResourceRecordSetCount": 2,
          "CallerReference": "test20150527-2",
          "Config": {
              "Comment": "test2",
              "PrivateZone": true
          },
          "Id": "/hostedzone/Z119WBBTVP5WFX",
          "Name": "dev.devx.company.services."
      },
      {
          "ResourceRecordSetCount": 2,
          "CallerReference": "test20150527-1",
          "Config": {
              "Comment": "test",
              "PrivateZone": true
          },
          "Id": "/hostedzone/Z3P5QSUBK4POTI",
          "Name": "test.devx.company.services."
      }
  ],
  "IsTruncated": false,
  "MaxItems": "100"
}

And my goal is to fetch a specific Name (in my case it's the test.devx.company.services), however the Name field contains an extra "." at the end that I'd like to remove from the output.

This is what I have so far:

jq --raw-output '.HostedZones[] | select(.Name | test("test")?) | (.Name[:-1] | sub("."; ""))'

The problem with that it is removing the first character from the output also.

So the output currently is: est.devx.company.services (JQ play snippet)

Not sure what I'm doing wrong :/

CodePudding user response:

To always remove the last character, if it contains "test":

jq '(.HostedZones[].Name | select(contains("test"))) |= .[:-1]'

To remove it only if it is a dot:

jq '(.HostedZones[].Name | select(contains("test"))) |= sub("[.]$"; "")'
  • Related