jq-如何基于属性值的“黑名单"选择对象 [英] jq - How to select objects based on a 'blacklist' of property values

查看:74
本文介绍了jq-如何基于属性值的“黑名单"选择对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于此处回答的问题: jq-如何基于属性值的白名单"选择对象,我想根据属性值黑名单...

Similar to the question answered here: jq - How to select objects based on a 'whitelist' of property values, I'd like to select objects based on a blacklist of property values...

以下内容可以很好地用作白名单:curl -s 'https://api.github.com/repos/stedolan/jq/commits?per_page=10' | jq --argjson whitelist '["stedolan", "dtolnay"]' '.[] | select(.author.login == $whitelist[]) | {author: .author.login, message: .commit.message}'

The following works fine as a whitelist: curl -s 'https://api.github.com/repos/stedolan/jq/commits?per_page=10' | jq --argjson whitelist '["stedolan", "dtolnay"]' '.[] | select(.author.login == $whitelist[]) | {author: .author.login, message: .commit.message}'

{
  "author": "dtolnay",
  "message": "Remove David from maintainers"
}
{
  "author": "stedolan",
  "message": "Make jv_sort stable regardless of qsort details."
}
{
  "author": "stedolan",
  "message": "Add AppVeyor badge to README.md\n\nThanks @JanSchulz, @nicowilliams!"
}

问题是,我想否定这一点,只显示"stedolan"和"dtolnay"以外的作者提交的内容;但是,如果使用!=not,我似乎会得到相同的错误结果:

The problem is, I want to negate that and only show commits from authors besides 'stedolan' and 'dtolnay'; however, if I use != or not, I seem to get the same wrong result:

nhenry@BONHENRY:~⟫ curl -s 'https://api.github.com/repos/stedolan/jq/commits?per_page=10' | jq --argjson blacklist '["stedolan", "dtolnay"]' '.[] | select(.author.login == $blacklist[] | not) | .author.login' | sort | uniq -c | sort -nr
     14 "nicowilliams"
      2 "stedolan"
      1 "dtolnay"
nhenry@BONHENRY:~⟫ curl -s 'https://api.github.com/repos/stedolan/jq/commits?per_page=10' | jq --argjson blacklist '["stedolan", "dtolnay"]' '.[] | select(.author.login != $blacklist[]) | .author.login' | sort | uniq -c | sort -nr
     14 "nicowilliams"
      2 "stedolan"
      1 "dtolnay"

有什么建议吗?

推荐答案

一种解决方案就是将indexnot一起使用:

One solution would simply be to use index with not:

.[] | .author.login | select( . as $i | $blacklist | index($i) | not)

但是,假设您的jq具有all/2,则使用它要说些什么:

However, assuming your jq has all/2, there is something to be said for using it:

.[] | .author.login | select( . as $i | all($blacklist[]; $i != .))

如果您的jq没有它,那么使用此解决方案还有一些要说的地方,all/2的定义如下:

If your jq does not have it, then there is still something to be said for using this solution, with all/2 defined as follows:

def all(s; condition): reduce s as $i (true; . and ($i | condition));

这篇关于jq-如何基于属性值的“黑名单"选择对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆