使用jq过滤值的json结果



我用jq过滤JSON结果时遇到问题。

我有以下JSON结果:

{"result":
[
"id":"799dbd172f409c65","status":"active","plan":{"planid":"0feeeeeeeeeeeeeeee","name":"Enterprise","externally_managed":true}}
"id":"a00eb4acb5905100","status":"active","plan":{"planid":"0feeeeeeeeeeeeeeee","name":"Enterprise","externally_managed":false}}
"id":"8e09545457675ed2","status":"active","plan":{"planid":"0feeeeeeeeeeeeeeee","name":"Enterprise","externally_managed":true}}
]}

我想得到一个帐户的ID列表;外部管理":是的。

我尝试使用以下JR,但一次又一次地失败。。。

jq -r '.result[] | select( .externally_managed | contains("true")) | "(.id)"'
jq -r '.result[] | select( .externally_managed == true) | "(.id)"'
jq -r '.result[] | select( .externally_managed|tostring == "true") | "(.id)"'

这种情况下的预期结果是:

799dbd172f409c65
8e09545457675ed2

任何协助都将不胜感激。

提前非常感谢!

有一个好的

假设您的JSON看起来更像这样(对象周围有大括号,数组项之间有逗号(:

{"result":
[
{"id":"799dbd172f409c65","status":"active","plan":{"planid":"0feeeeeeeeeeeeeeee","name":"Enterprise","externally_managed":true}},
{"id":"a00eb4acb5905100","status":"active","plan":{"planid":"0feeeeeeeeeeeeeeee","name":"Enterprise","externally_managed":false}},
{"id":"8e09545457675ed2","status":"active","plan":{"planid":"0feeeeeeeeeeeeeeee","name":"Enterprise","externally_managed":true}}
]}

您的三次尝试都没有成功降落到.plan对象中。除此之外,所有操作都很好,只有第一个操作在应用contains之前需要转换为字符串(正如您在第三个操作中已经做的那样(:

$ jq -r '.result[] | select(.plan.externally_managed|tostring | contains("true")) | "(.id)"'
799dbd172f409c65
8e09545457675ed2
$ jq -r '.result[] | select(.plan.externally_managed == true) | "(.id)"'
799dbd172f409c65
8e09545457675ed2
$ jq -r '.result[] | select(.plan.externally_managed|tostring == "true") | "(.id)"'
799dbd172f409c65
8e09545457675ed2

这是另一个较短的方法,它直接使用select的布尔值,并省略了将.id的值转换为字符串(至少在您的示例数据中已经准备好了(:

$ jq -r '.result[] | select(.plan.externally_managed).id'
799dbd172f409c65
8e09545457675ed2

演示

相关内容

  • 没有找到相关文章

最新更新