【问题标题】:Filter out entries in child array过滤子数组中的条目
【发布时间】:2019-02-13 11:49:26
【问题描述】:

如何过滤 json 子数组中的项目?

例如,这样:

{
  "country": "Australia",
  "cities": [
    "Melbourne",
    "Sydney",
    "Brisbane",
    "Perth"
  ]
}

我需要过滤掉“布里斯班”和“珀斯”才能获得。

{
  "country": "Australia",
  "cities": [
    "Melbourne",
    "Sydney"
  ]
}

我尝试了select(something|test("Brisbane|Perth")|not) 的不同组合,但没有成功。

【问题讨论】:

    标签: arrays json select jq


    【解决方案1】:

    你可以使用减法:

    jq '.cities -= ["Perth", "Brisbane"]'
    

    输出:

    {
      "country": "Australia",
      "cities": [
        "Melbourne",
        "Sydney"
      ]
    }
    

    【讨论】:

    • 比我的回答简单多了!
    • 更简单:.cities -= ["Perth", "Brisbane"]
    • 没有比.cities -= ["Perth", "Brisbane"] 更简单的了。谢谢
    • @peak:我喜欢
    【解决方案2】:

    您可以将更新赋值运算符|=map 结合使用

    jq '.cities|=map(if . == "Brisbane" or . == "Perth" then empty else . end)'
    

    【讨论】:

    • 我已经接受了 Thor 的简单回答,但您的回答更灵活,可以进行子字符串匹配。例如:'.cities |= map(if test("Per|Bris") then empty else . end)'
    猜你喜欢
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 2017-11-02
    • 1970-01-01
    相关资源
    最近更新 更多