【问题标题】:jq - select an object based on existence of a propertyjq - 根据属性的存在选择一个对象
【发布时间】:2019-08-08 11:11:52
【问题描述】:

乍一看,这听起来非常简单,但我已经做了好几个小时了。

我正在尝试提取参数对象的名称(无法知道),但前提是它列出了“defaultValue”键。

输入对象(Azure ARM 模板):

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "componentName": {
            "defaultValue": "storage",
            "type": "string"
        },
        "subnetId": {
            "type": "string",
            "metadata": {
                "description": "The subnet to which this storage component belongs."
            }
        }
    },
    "variables": {}
}

期望的输出:

    "componentName": {
        "defaultValue": "storage",
        "type": "string"
    }

我已经尝试了以下多次迭代,但均未成功:

.parameters[] | select(  has( "defaultValue")) 

(将对象扩展到其名称“componentName”之外 - 尽管这确实正确找到了两者的匹配对象)

.parameters | map(select(has("defaultValue"))) 

(同上)

.parameters | select( any (has( "defaultValue"))) 

(这也错误地返回了不具有“defaultValue”属性的 SubnetId 对象)

显然我误解了一些基本的东西。我将不胜感激任何可以提供的建议或指导。

【问题讨论】:

    标签: json jq


    【解决方案1】:

    您想要的输出不是有效的 JSON。我知道的最接近(没有自定义字符串格式)是:

    jq '.parameters | map_values(select(has("defaultValue")))'
    # => {
    #      "componentName": {
    #        "defaultValue": "storage",
    #        "type": "string"
    #      }
    #    }
    

    【讨论】:

      猜你喜欢
      • 2014-08-04
      • 2016-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-03
      • 1970-01-01
      • 2019-08-10
      • 2019-08-16
      相关资源
      最近更新 更多