I’m trying to merge some json objects using jq.
It seems to complicated for me ^^
I have a json which looks like this
[
{
"name": "test_name",
"cpu": "1",
"ip": "192.168.0.1",
"kv_key": "test2_key",
"kv_value": "test2_value",
"location": "here"
},
{
"name": "test_name",
"cpu": "1",
"ip": "192.168.0.2",
"kv_key": "test1_key",
"kv_value": "test1_value",
"location": "here"
},
{
"name": "test_name",
"cpu": "1",
"ip": "192.168.0.1",
"kv_key": "test2_key",
"kv_value": "test2_value",
"location": "here"
},
{
"name": "test_name",
"cpu": "1",
"ip": "192.168.0.1",
"kv_key": "test3_key",
"kv_value": "test3_value",
"location": "here"
}
]
And I want something like this
[
{
"name": "test_name",
"cpu": "1",
"ip": [
"192.168.0.1",
"192.168.0.2"
],
"key_value": [
{
"test1_key": "test1_value",
"test2_key": "test2_value",
"test3_key": "test3_value"
}
],
"location": "here"
}
]
I managed to make something work for the ip field only
jq 'map(. |= (group_by(.name) | map(first + {ip: map(.ip)})))' <<< "${json}"
Probably not the best way to do this and I’m clearly stuck on the key/value part.
Thx for you help !
amans
2
Answers
You can try:
If all items have the same keys, you can make this generic by using
to_entries
to split the objects into an array of key-value pairs,transpose
them, and combine them again usingfrom_entries
. Duplicate values can be eliminated usingunique
, and singletons can be generated by checking for the presence of a second item usingselect(has(1))
: