I'm delete all entries that do not have any dependencies, but I as I don't know jq very well, I am also having problem finding an answer.
I have:
{
"dev": {
"Alpha": {
"dependencies": [
"Gamma",
"Delta"
],
"other_value_1": [
"aaa"
],
"other_value_n": [
"unknown number of other values"
]
},
"Beta": {
"package_name": "some name",
"scm": {
"type": "git",
"url": "git url"
}
},
"Gamma": {
"dependencies": [
"Delta"
]
},
"Delta": {
"dependencies": []
}
}
}
Out of which I want to get only the names (Alpha, Gamma) and only with dependencies inside:
{
"dev": {
"Alpha": {
"dependencies": [
"Gamma",
"Delta"
]
},
"Gamma": {
"dependencies": [
"Delta"
]
}
}
}
Let's assume that there may be many unforeseen values besides dependencies
CodePudding user response:
Slightly more verbose way, without specifying the keys:
.dev |= with_entries(select(.value.dependencies | length > 0) | .value = { dependencies: .value.dependencies})
Using with_entires()
to select()
those where .value.dependencies
has length > 0
, then set (|=
) value
to an object only containing the dependencies
Will output:
{
"dev": {
"Alpha": {
"dependencies": [
"Gamma",
"Delta"
]
},
"Gamma": {
"dependencies": [
"Delta"
]
}
}
}
CodePudding user response:
Here's one way using the Object construction shortcut {name}
:
jq '.dev |= ({Alpha, Gamma} | .[] |= {dependencies})'
If the keys filtered should be dynamic, selecting on has(0)
can test for the existence of a first array item, i.e. for a non-empty list:
jq '.dev[] |= ({dependencies} | select(.[] | has(0)))'
Output:
{
"dev": {
"Alpha": {
"dependencies": [
"Gamma",
"Delta"
]
},
"Gamma": {
"dependencies": [
"Delta"
]
}
}
}
CodePudding user response:
Assuming dependencies
is either an array or nonexistent:
.dev |= map_values(
select(
.dependencies
| IN(null, [])
| not
)
| {dependencies}
)