How to parse a JSON to when a few values are string and other are list.
I have a list like this:
{
"abc": {
"enabled": true
},
"def": {
"enabled": false
},
"ghi": [
{
"enabled": false,
"name": "HELLO",
"useless": "DO NOT WANT THIS"
}
],
"jkl": [
{
"enabled": true,
"name": "HI"
}
],
"mko": {
"enabled": false,
"something unwanted": 123
},
"pqr": {
"enabled": true
}
}
Trying to filter only by the two key(enabled
and name like abc
):
{
"abc": {
"enabled": true
},
"def": {
"enabled": false
},
"ghi": [
{
"enabled": false,
"name": "HELLO"
}
],
"jkl": [
{
"enabled": true,
"name": "HI"
}
],
"mko": {
"enabled": false
},
"pqr": {
"enabled": true
}
}
Tried several answers on SO, but nothing is giving the desired result. I am not a regular consumer of JSON so this question might sounds stupid.
jq -r '[*].enabled' file
jq: error: syntax error, unexpected '*' (Unix shell quoting issues?) at <top-level>, line 1:
[*].enabled
jq: 1 compile error
CodePudding user response:
You can use a combination of objects
and arrays
to select the items to update with |=
, then with_entries
to access the .key
which can be queried with IN
:
< file jq '
(.[] | objects, (arrays[] | objects))
|= with_entries(select(.key | IN("enabled", "name")))
'
{
"abc": {
"enabled": true
},
"def": {
"enabled": false
},
"ghi": [
{
"enabled": false,
"name": "HELLO"
}
],
"jkl": [
{
"enabled": true,
"name": "HI"
}
],
"mko": {
"enabled": false
},
"pqr": {
"enabled": true
}
}