I have a json file like this
[
"public-policy-routing/0",
"public-policy-routing/1",
"public-policy-routing/5",
"public-policy-routing/7",
"public-policy-routing/10"
]
since the element has pattern "key/values" where only values part differ I want to reduce the output to something like this
{ "public-policy-routing" : [0,1,5,7,10] }
any idea how to achieve above using jq ?
CodePudding user response:
One way would be using reduce
on the array elements. Split at the slash, destructure the resulting array into a key and value variable, then add the value as an array to the field with the key name:
jq 'reduce (.[]/"/") as [$k,$v] ({}; .[$k] = [$v])'
{
"public-policy-routing": [
"0",
"1",
"5",
"7",
"10"
]
}
If you wanted numbers instead of strings, convert the values using tonumber
:
jq 'reduce (.[]/"/") as [$k,$v] ({}; .[$k] = [$v | tonumber])'
{
"public-policy-routing": [
0,
1,
5,
7,
10
]
}
CodePudding user response:
Here is a mildly robust solution:
def ton: try tonumber catch .;
def keysplit: index("/") as $i
| if $i then [.[:$i], (.[$i 1:]|ton) ] else [., ""] end;
reduce ( .[]|keysplit ) as [$k,$v] ({}; .[$k] = [$v] )