Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jq handling empty strings and replacing them with a default value

Tags:

json

bash

jq

I currently have a json file I am manipulating with jq. I am able to display it how I want for the most part. However, I am running into a problem when displaying values for a field that's empty. I am using the // alternative operator but it is not returning the desired output. What is the right way to handle empty strings with jq?

Current Output:

RELEASE    INSTALLED  LATEST  DEPRECATED
test-app   1.0.0      2.0.0   false
test-app2  3.0.0      true

Desired Output:

RELEASE    INSTALLED  LATEST  DEPRECATED
test-app   1.0.0      2.0.0   false
test-app2  3.0.0      -        true

Jq:

cat test1.json | jq -r 'map({release, installed: .Installed.version, latest: (.Latest.version // "-"), deprecated}) | ( .[0] | keys_unsorted | map(ascii_upcase)), (.[] | [.[]]) | @tsv' | column -t

Json:

[
  {
    "release": "test-app",
    "Installed": {
      "version": "1.0.0",
      "appVersion": ""
    },
    "Latest": {
      "version": "2.0.0",
      "appVersion": ""
    },
    "outdated": true,
    "deprecated": false
  },
  {
    "release": "test-app2",
    "Installed": {
      "version": "3.0.0",
      "appVersion": ""
    },
    "Latest": {
      "version": "",
      "appVersion": ""
    },
    "outdated": false,
    "deprecated": true
  }
]
like image 537
MaryCoding Avatar asked Oct 24 '25 14:10

MaryCoding


2 Answers

If empty string "" is the only case you want to treat as null, you could just use the alternative operator to force to it then replace as needed.

.Latest.version // "" | select(. != "") // "-"

# or using if-then-else
.Latest.version // "" | if . == "" then "-" else . end

# or if you're using the latest dev version, else is optional
.Latest.version // "" | if . == "" then "-" end
like image 199
Jeff Mercado Avatar answered Oct 26 '25 05:10

Jeff Mercado


"" is not classed as null as Philippe pointed out, but if you're unable to change the json to make the "" become null, what you can do is

jq -r 'map({release, installed: .Installed.version, latest: (if .Latest.version == "" then "-" else .Latest.version end), deprecated}) | ( .[0] | keys_unsorted | map(ascii_upcase)), (.[] | [.[]]) | @tsv' data.json | column -t
like image 45
644 Avatar answered Oct 26 '25 03:10

644



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!