'How to create a specific result using JQ (jq parse json)
I have massive like this:
2254003131908096 39480500160 39763833120
2296334329577472 36713833920 37747166400
2297708719112192 39830499360 41430500640
Which JQ command should I use to get the result like this:
"2254003131908096": {
{
"exchange": "39480500160",
"replication": "39763833120"
}
}
"2296334329577472": {
{
"exchange": "36713833920",
"replication": "39763833120"
}
}
"2297708719112192": {
{
"exchange": "39830499360",
"replication": "41430500640"
}
}
Help me please.
Solution 1:[1]
Your sample output is invalid JSON. I assume you want to have one object with one field per input row.
Read in raw text using -R
, then split by space using /
, and reduce all the input to one object by setting the according fields.
jq -Rn '
[inputs / " "] | reduce .[] as $line ({};
.[$line[0]] = {exchange: $line[1], replication: $line[2]}
)
'
{
"2254003131908096": {
"exchange": "39480500160",
"replication": "39763833120"
},
"2296334329577472": {
"exchange": "36713833920",
"replication": "37747166400"
},
"2297708719112192": {
"exchange": "39830499360",
"replication": "41430500640"
}
}
Solution 2:[2]
You can use reduce
.
Filter
reduce (inputs / " " ) as [$k,$e,$r] ({}; .+{($k):{exchange:$e,replication:$r}})
Input
2254003131908096 39480500160 39763833120
2296334329577472 36713833920 37747166400
2297708719112192 39830499360 41430500640
Output
{
"2254003131908096": {
"exchange": "39480500160",
"replication": "39763833120"
},
"2296334329577472": {
"exchange": "36713833920",
"replication": "37747166400"
},
"2297708719112192": {
"exchange": "39830499360",
"replication": "41430500640"
}
}
Demo
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | pmf |
Solution 2 | Logan Lee |