【问题标题】:With jq how to get the name of the parent element that contains "DOWN"?用jq如何获取包含“DOWN”的父元素的名称?
【发布时间】:2020-08-28 14:15:36
【问题描述】:
{
      "status": "DOWN",
      "components": {
          "ping": {
              "status": "UP",
              "details": {
                  "version": "1.0.0",
                  "description": "dobre application",
                  "name": "SO-3113"
              }
          },
          "bridge.lock": {
              "status": "UP",
              "details": {
                  "description": "test1"
              }
          },
          "Configuration converted": {
              "status": "DOWN",
              "details": {
                  "description": "test2"
              }
          },
          "app started": {
              "status": "DOWN",
              "details": {
                  "description": "test3"
              }
          }
      }
  }

我需要获取具有 DOWN 状态的第一个组件的名称(上述 json 中的“配置转换”)。到目前为止,我只得到了.details.description

jq -c '.components| .[] | select( .status | contains("DOWN")) .details.description' | head -1

如何获取组件的名称(键)? (“配置转换”)

【问题讨论】:

  • 我不清楚你的问题,我在jqplay.org 中使用你的 json 执行了你的查询,它返回给我:“test2”“test3”。你能告诉我你想要的输出是什么吗?
  • 需要“配置转换”,因为这首先包含“DOWN”。对不起我的英语不好

标签: jq


【解决方案1】:

您可以使用to_entries 获取组件的键/值,然后选择第一个状态为向下的:

first(.components | to_entries | .[] | select( .value.status == "DOWN") | .key)

Run it on jqplay

【讨论】:

  • 还要注意对象键的顺序没有实际意义,如果要保持顺序,应该使用数组而不是对象:stackoverflow.com/a/7214316/4718434
  • 最好避免contains/1,它充其量是语义复杂的,而且似乎不符合这里的要求。使用== 进行检查就足够了。
  • @peak 同意,更新了答案。
【解决方案2】:

您可以使用to_entries 函数将.components 中的对象转换为键/值对,并提供一个表达式来选择与条件匹配的第一个对象并检索其键

.components | 
to_entries  | 
map(select(.value.status == "DOWN"))[0].key

【讨论】:

    猜你喜欢
    • 2014-03-01
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多