{
"vehicle": [
{
"type": "car",
"features": [
{
"airbags": "yes",
"engine": [
{
"electric": "yes",
"horsepower": "1000"
}
],
"number": "ABCD 1234"
}
],
"price": "100000"
},
{
"type": "truck",
"features": [],
"price": "500000"
},
{
"type": "train",
"features": [
{
"airbags": "no",
"engine": [
{
"horsepower": "10000"
}
],
"number": "MNOPQRST"
}
],
"price": "100000"
}
]
}
使用jq
or jmespath
,我想要type
其中的值vehicle[].features[]
是空数组或缺少vehicle[].features[].engine[].electric
元素。
所以这个 json 应该列出我truck
,train
因为卡车有一个空数组vehicle[].features[]
,而火车缺少vehicle[].features[].engine[].electric
元素。
答案1
鉴于您的特定输入看起来features
并且engines
始终最多有一个元素,您应该能够执行以下操作:
jq -r '.vehicle[] | select(.features[0].engine[0].electric != "yes").type'
或者:
jq -r '.vehicle[] | select(.features[0].engine[0] | has("electric") | not).type'
对于那些第一个拥有钥匙的type
人来说。vehicle
engine
features
not
electric
或者,如果像我一样,您perl
已经了解另一种编程语言,并且不想学习另一种(而且非常具体的)语言,例如jq
s:
perl -MJSON -l -0777 -ne '
$j = from_json($_);
for (@{$j->{vehicle}}) {
print $_->{type} unless $_->{features}[0]->{engine}[0]->{electric} eq "yes"
}' < file.js
(或者unless defined($_->{features}[0]->{engine}[0]->{electric})
)。