'Matching When Value Is List
I have an API dump file that is similar to this.
{
"abc": {
"Code": "ABC",
"Type": [] },
"def": {
"Code": "DEF",
"Type": [
"A"
]
},
"ghi": {
"Code": "GHI",
"Type": [
"B"
]
},
"jkl": {
"Code": "JKL",
"Type": [
"A",
"B"
]
},
"mno": {
"Code": "MNO",
"Type": [ "Universal" ]
}
}
I am trying to extract objects, and get Code keys based on certain Type matches.
For example. Trying to where Type matches "A", "B", "A, B", or Universal, I am getting objects that contain both, or nothing in certain cases.
Here is what I tried.
jq -r '.[] | select(.Type[] == "A") | .Code' /tmp/test.json
I get
DEFWhich is unexpectedly matching Type ["A"} and Type ["A", "B"]
JKL
jq -r '.[] | select(.Type[] == "B") | .Code' /tmp/test.json
I get.
GHIWhich is unexpectedly matching Type ["B"} and Type ["A", "B"]
JKL
jq -r '.[] | select(.Type[] == "A, B") | .Code' /tmp/test.json
Matches nothing.
This works as expected.
jq -r '.[] | select(.Type[] == "Universal") | .Code' /tmp/test.json
MNO
Solution 1:[1]
If you wanted exact match, save following into script.jq :
.[] | select(.Type == $match) | .Code
Then test with
$ jq -r --argjson match '["A"]' -f script.jq test.json
DEF
$ jq -r --argjson match '["B"]' -f script.jq test.json
GHI
$ jq -r --argjson match '["A", "B"]' -f script.jq test.json
JKL
Solution 2:[2]
The jq program
.[] | select(any(.Type[]; IN("A","B","A, B","Universal"))) | .Code
produces:
"DEF"
"GHI"
"JKL"
"MNO"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Philippe |
| Solution 2 |
