ozimki
ozimki

Reputation: 125

jq merge json array elements

I have my data in the following json array:

[{ "min": 1, "max": 2},
 { "min": 5, "max": 6}]

and I would need to have it in the format:

1-2,5-6

I have tried the following filter:

.[] | [ .min, .max|tostring ] | join("-")

and I ended up having:

"1-2"
"5-6"

I do not know how to get from that to expression to the desired "1-2","5-6". I am new to jq and would appreciate any hints.

Upvotes: 3

Views: 155

Answers (2)

hek2mgl
hek2mgl

Reputation: 157947

Also string interpolation could be used, in combination with join:

jq -r 'map("\(.min)-\(.max)") | join(",")' file.json

Thanks to peak for the idea.

Upvotes: 2

peak
peak

Reputation: 116690

jq -r 'map([.min, .max|tostring] | join("-")) | join(",")' input.json
1-2,5-6

If you have a sufficiently recent version of jq, you can drop the call to tostring.

If the min/max elements are always in that order and if there are no other keys, you might like to consider:

map([.[]] | join("-")) | join(",")

Upvotes: 3

Related Questions