首页 > 解决方案 > 使用 JQ 提取数据

问题描述

我正在尝试使用 jq 从包含特定值的 JSON 字段中提取数据。

这是我正在使用的 JSON:

{
  "thing1": {
    "a": false,
    "b": true,
    "c": false,
    "d": false
  },
  "thing2": {
    "a": true,
    "b": true,
    "c": true,
    "d": true
  },
  "thing3": {
    "a": true,
    "b": false,
    "c": false,
    "d": false
  }
}

我想保留包含"true"值的对象,并删除值不是的键true

我对 JQ 没有太多经验,也没有如何正确构造 json 数据。如果这意味着重构主要的 JSON 数据,我也愿意这样做。

这是我想要达到的结果:

{
  "thing1": {
    "b": true
  },
  "thing2": {
    "a": true,
    "b": true,
    "c": true,
    "d": true
  },
  "thing3": {
    "a": true
  }
}

标签: jsondictionaryjq

解决方案


# First remove the subkeys that are not truthy:
map_values(with_entries(select(.value)))
# ... then remove the empty dictionaries:
| with_entries(select(.value|length > 0))

加入调味料调味。


推荐阅读