How can I get the first x levels of depth of an object and remove the rest using jq ?
I have the following example:
{
"Service1": {
"Production": {
"Location 1": {
"b2d1": {
"clusters": {
"Datacenter2": []
},
"prod": {
"clusters": {
"Datacenter1": []
}
}
}
},
"Service2": {
"Production": {
"Location 1": {
"dr1": {
"clusters": {
"Datacenter3": []
},
"prod": {
"clusters": {
"Datacenter1": []
}
}
}
}
}
}
}
}
}
In my case, I want to get the 1st 3 levels (want to remove everything bellow location in all entries.
3
Answers
You could get all the
paths
oflength > 3
(actually== 4
would suffice), and delete those usingdelpaths
:Demo
Note that
Service2
is already on third level, so it is cut off immediately (without going down to its ownLocation 1
field).Here is one way:
From the question and example, it’s not too clear how arrays should be handled, so the following may be of interest as it makes a clear distinction between JSON objects and all else:
For the sample input, the output would be: