Using jq how can I replace the key name with something else
This should be simple enough ... I want to rename multiple keys (ideally with jq), whatever I do seems to be a bug. Here is a json example below:
[
{
"fruit": "strawberry",
"veg": "apple",
"worker": "gardener"
}
]
I would like to rename the veg key to fruit2 (or whatever one may say), as well as the working key to work.
I understand that this is possible in Sed, but I am trying to deal with JQ
+11
user3229731
source
to share
2 answers
Use the following jq approach :
jq '[.[] | .["fruit2"] = .veg | .["job"] = .worker | del(.veg, .worker)]' file
Output:
[
{
"fruit": "strawberry",
"fruit2": "apple",
"job": "gardener"
}
]
+9
RomanPerekhrest
source
to share
The key (:-) is with_entries. For example, for one object:
with_entries(if .key == "veg" then .key = "fruit2" else . end)
In your case, since you have an array of objects, you can wrap this in map( ... )
.
+5
peak
source
to share