I have the following JSON;
[
{
"id": 1,
"start": "2022-06-20",
"result": 24
},
{
"id": 2,
"start": "2022-06-21",
"result": 56
},
{
"id": 3,
"start": "2022-06-21",
"result": 78
}
]
I'm wanting to add 2 new values to each array above using JQ, dimension
and date
, but date
needs to be a copy of the existing key value start
. The expected output is as below;
[
{
"id": 1,
"start": "2022-06-20",
"result": 24,
"date": "2022-06-20",
"dimension": "new"
},
{
"id": 2,
"start": "2022-06-21",
"result": 56,
"date": "2022-06-21",
"dimension": "new"
},
{
"id": 3,
"start": "2022-06-21",
"result": 78,
"date": "2022-06-21",
"dimension": "new"
}
]
The jq I have at present can add the new key dimension
, but I can't figure out how to copy start -> date
jq '.[] = {"dimension": "new"}' input.json
Thanks for any help
CodePudding user response:
Just create the new key / value pairs.
jq 'map(.date = .start | .dimension = "new")' input.json
CodePudding user response:
You might have tried the following:
.[] = { date: .start, dimension: "new" } // WRONG
But it's not quite right since .
is the array, not the element of the array. You can use |=
as a topicalizer.
.[] |= ( . = { date: .start, dimension: "new" } )
But I'd use map
instead.
map( . = { date: .start, dimension: "new" } )
Alternatively,
. = { date: .start, dimension: "new" }
can also also be achieved using
.date = .start | .dimension: "new"
So you could use
.[] |= ( .date = .start | .dimension: "new" )
or
map( .date = .start | .dimension = "new" )