0

Using a JSON file with the following content:

{"major":a, "minor":b, "hotfix":c}

I'm trying to use jq to generate the following output:

a.b.c

I've used individual jq commands, such as jq .major and I'm able to individually get the content I need, but doing it all at once, and especially, adding the dots, is proven to be difficult for me.

Thank you.

5

jq has a join function for exactly this situation:

jq '[.major,.minor,.hotfix] | map (tostring) | join(".")'

You can leave out the map if the values are already strings.

  • That's awesome! Very clean approach. Thank you very much for sharing! – t988GF Oct 9 '18 at 19:20
1

Use the jq commands in a series of command substitutions into a variable assignment that hard-codes a period between them:

output="$(jq .major ...)"."$(jq .minor ...)"."$(jq .hotfix ...)"
1
jq -j '.major, ".", .minor, ".", .hotfix, "\n"' file

just in case someone doesn't get it, this is what the man page says:

Even literals like "hello" or 42 are filters - they take an input but always produce the same literal as output.

....

, If two filters are separated by a comma, then the input will be fed into both and there will be multiple outputs: first, all of the outputs produced by the left expression, and then all of the outputs produced by the right.

So no need for any complications like | map | join / whatever in such simple cases. Maybe the man page should be better structured.

0

And supposing jq wasn't available, GNU awk solution:

awk -F':|,|}' '{print $2"."$4"."$6}' file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.