I'd like to add leading/trailing zeros to strings from numbers — resultant string needs to contain "01" or "001" and not "1". I noticed project https://github.com/joelpurra/jq-zeros
but I have jq installed from package manager (dnf, fedora) so requirement of some jqnpm
is not feasible for me (at first sight), not to mention my fear of npm, as stuff sudo npm -g
ruined my system several times already.
Question:
Given this JSON document:
7
You can achieve "007"
with the following filter: (or "042"
with 42
)
tostring | (length | if . >= 3 then "" else "0" * (3 - .) end) as $padding | "\($padding)\(.)"
tostring
convert 7
into "7"
""
otherwise set to "0" * (3 - length)
. (When a string is multiplied by a number it is repeated that many time e.g. "foo" * 3
-> "foofoofoo"
)