【问题标题】:Why is my jq `select` returning two values?为什么我的 jq `select` 返回两个值?
【发布时间】:2019-11-06 17:21:38
【问题描述】:

在下面的示例中,我想要一个所有有家具的房子的列表。

[
  {
    "id": "jones house",
    "rooms": [
      {
        "name": "living room",
        "furniture": {
          "chair": "red"
        }
      },
      {
        "name": "bedroom",
        "furniture": {
          "chair": "blue"
        }
      },
            {
        "name": "bathroom",
        "furniture": {
        }
      }
    ]
  },
  {
    "id": "smith house",
    "rooms": [
      {
        "name": "basement",
        "furniture": {
          "chair": "green"
        }
      }
    ]
  },
  {
    "id": "johnson house",
    "rooms": [
      {
        "name": "study",
        "furniture": {
        }
      }
    ]
  }
]

我正在应用以下 jq 语句:.[] | select(.rooms[].furniture | length > 0) | .id,我将其读作:

  1. 对于数组中的每个元素,通过管道发送它。
  2. 如果选择条件为真,则通过管道发送未更改的输入元素。
  3. 输出id属性。

我期待:

"jones house"
"smith house"

输出看起来像这样:

"jones house"
"jones house"
"smith house"

https://stedolan.github.io/jq/manual/#select(boolean_expression) 状态:

如果 foo 对该输入返回 true,则函数 select(foo) 会产生其输入不变,否则不产生任何输出。

如果select 只能产生它的输入,不变,它怎么能产生两个“jones house”输出?

JQPlay:https://jqplay.org/s/beaibywO2k

【问题讨论】:

    标签: json jq


    【解决方案1】:

    第一个rooms 有两个符合length > 0 的对象,因此它被选中并打印了两次。使用any 获得您想要的输出:

    .[] | select(any(.rooms[].furniture; length > 0)) | .id
    

    jqplay demo

    【讨论】:

    • 这行得通,谢谢。不过,这似乎与文档背道而驰,文档中说它“产生的输入不变”。它产生了两次输入。
    • @Crunch 我认为你误解了那部分。它仍然产生不变的输入,但选择了两次
    • 是的。我认为它的编写方式很容易被误解。无论如何,感谢您的帮助。
    猜你喜欢
    • 2014-03-20
    • 2011-08-09
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多