根据其值的属性过滤对象

时间:2017-10-26 06:46:47

标签: json filter jq

我试图使用jq来过滤json块。我需要保留完整的结构,但过滤掉了不可配置的"孩子json块。

{
  "properties": {
    ".properties.backup_options": {
      "type": "selector",
      "configurable": true,
      "credential": false,
      "value": "disable",
      "optional": false
    },
    ".properties.backup_options.enable.cron_schedule": {
      "type": "string",
      "configurable": true,
      "credential": false,
      "value": null,
      "optional": false
    },
    ".properties.backup_options.enable.backup_all_masters": {
      "type": "boolean",
      "configurable": true,
      "credential": false,
      "value": true,
      "optional": false
    },
    ".properties.backups": {
      "type": "selector",
      "configurable": false,
      "credential": false,
      "value": "disable",
      "optional": false
    },
    ".properties.backups.enable.endpoint_url": {
      "type": "string",
      "configurable": false,
      "credential": false,
      "value": null,
      "optional": true
    }
}

我已经能够过滤掉cat input.json | jq '.properties[] | select(.configurable==true)',但这会失去原有的结构。

奖励标记也过滤掉子块中的一些字段,即删除凭证和类型行。

所以期望的输出是:

{
  "properties": {
    ".properties.backup_options": {
      "configurable": true,
      "value": "disable",
      "optional": false
    },
    ".properties.backup_options.enable.cron_schedule": {
      "configurable": true,
      "value": null,
      "optional": false
    },
    ".properties.backup_options.enable.backup_all_masters": {

      "configurable": true,
      "value": true,
      "optional": false
    }       
}

我是否需要嵌套多个jq语句才能实现此目的?打破它并重建?帮助(这已经耗费了太多时间尝试不同的组合和教程)。

2 个答案:

答案 0 :(得分:3)

因此,您实际上是在获取一个对象并选择要保留的属性(或要删除的属性)。只需选择它们。

我们正在对properties对象进行更新,以便更新并选择(保留)所需的属性。过滤后,映射出要保留在结果中的属性:

$ jq '.properties |=
with_entries(select(.value.configurable)
  | .value |= {configurable,value,optional}
)' input.json

答案 1 :(得分:2)

此过滤器将为您提供"configurable": true

的属性
 .properties |= reduce keys[] as $k (.; 
     if .[$k].configurable 
     then . 
     else delpaths([[$k]]) end
  ) 

Try it online at jqplay.org

此过滤器演示了如何进一步优化属性到键的子集:

 .properties |= reduce keys[] as $k (.; 
     if   .[$k].configurable 
     then .[$k] |= {configurable,value,optional} 
     else delpaths([[$k]]) end
 )

示例输出

{
  "properties": {
    ".properties.backup_options": {
      "configurable": true,
      "value": "disable",
      "optional": false
    },
    ".properties.backup_options.enable.cron_schedule": {
      "configurable": true,
      "value": null,
      "optional": false
    },
    ".properties.backup_options.enable.backup_all_masters": {
      "configurable": true,
      "value": true,
      "optional": false
    }
  }
}

Try it online at jqplay.org

使用辅助功能,例如

def objmap(cond;update): reduce keys[] as $k (.; 
   if .[$k]|cond then .[$k]|=update else delpaths([[$k]]) end
);

过滤器可以写成

.properties |= objmap(.configurable; .)

.properties |= objmap(.configurable; {configurable,value,optional})