过滤嵌套对象中的部分

huangapple go评论57阅读模式
英文:

Filtering out sections in nested object

问题

以下是您要的翻译的内容:

{
  "foo": {},
  "bar": {
    "a": {
      "tags": [
        "x",
        "y"
      ],
      "cycle": "simple"
    }
  },
  "qux": {
    "d": {
      "tags": [
        "x",
        "y",
        "z"
      ],
      "cycle": "complex"
    }
  }
}
英文:

Given the following json:

{
  "foo": {},
  "bar": {
    "a": {
      "tags": [
        "x",
        "y"
      ],
      "cycle": "simple"
    },
    "b": {
      "tags": [
        "x"
      ],
      "cycle": null
    }
  },
  "baz": {
    "c": {
      "tags": [
        "y"
      ],
      "cycle": null
    }
  },
  "qux": {
    "d": {
      "tags": [
        "x",
        "y",
        "z"
      ],
      "cycle": "complex"
    }
  }
}

I'd like to drop all objects in the top-level object which have "cycle == null". When filtering for "cycle", I don't know how to access fields from earlier filters:

$ jq '.[] | .[] | select(.cycle != null)' data.json
{
  "tags": [
    "x",
    "y"
  ],
  "cycle": "simple"
}
{
  "tags": [
    "x",
    "y",
    "z"
  ],
  "cycle": "complex"
}

I'd like to keep the structure of the matching entries, something like this:

{
  "bar": {
    "a": {
      "tags": [
        "x",
        "y"
      ],
      "cycle": "simple"
    }
  },
  "qux": {
    "d": {
      "tags": [
        "x",
        "y",
        "z"
      ],
      "cycle": "complex"
    }
  }
}

I was hoping to write something like this jq '.*.*. | select(.cycle != null)' so that I wouldn't need to manually re-assemble the original structure, but didn't understand wildcards.

答案1

得分: 1

.[] |= …(或 map_values(…))允许您操作对象的内容,而不会丢失外部结构。嵌套使用两次可以深入到两个级别。select(.cycle != null) 是您的主要筛选条件,但我还添加了 select(. != {}) 在中间级别,因为您的期望输出不包括 "foo": {}

jq '.[] |= (.[] |= select(.cycle != null) | select(. != {}))'
{
  "bar": {
    "a": {
      "tags": [
        "x",
        "y"
      ],
      "cycle": "simple"
    }
  },
  "qux": {
    "d": {
      "tags": [
        "x",
        "y",
        "z"
      ],
      "cycle": "complex"
    }
  }
}

演示

英文:

.[] |= … (or map_values(…)) lets you manipulate the contents of objects without losing the outer structure. Nest it twice to go two levels deep. select(.cycle != null) is your main filter, but I've also added select(. != {}) on the intermediate level as your desired output didn't include "foo": {}.

jq '.[] |= (.[] |= select(.cycle != null) | select(. != {}))'
{
  "bar": {
    "a": {
      "tags": [
        "x",
        "y"
      ],
      "cycle": "simple"
    }
  },
  "qux": {
    "d": {
      "tags": [
        "x",
        "y",
        "z"
      ],
      "cycle": "complex"
    }
  }
}

Demo

huangapple
  • 本文由 发表于 2023年5月25日 20:24:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76332247.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定