【问题标题】:How do you exclude a property?如何排除属性?
【发布时间】:2017-10-25 23:27:34
【问题描述】:

我有以下数据集:

[
  {
    "py/object": "bit.ast.Node",
    "_children": [
      {
        "py/object": "bit.ast.Node",
        "_children": [
          "main",
          {
            "py/object": "bit.ast.Node",
            "_children": [
              "args",
              {
                "py/object": "bit.ast.Node",
                "_children": [
                  {
                    "py/object": "bit.ast.Node",
                    "_children": [
                      "str"
                    ],
                    "source_column": 2,
                    "source_filename": "tests/fixture/hello.b",
                    "source_line": 1,
                    "tag": "type-named"
                  }
                ],
                "base": {
                  "py/id": 10
                },
                "source_column": 2,
                "source_filename": "tests/fixture/hello.b",
                "source_line": 1,
                "tag": "type",
                "type": "array"
              }
            ],

(等等……)

如何让jq_children 属性从所有拥有它的对象中排除?那么所有以_ 开头的属性呢?

以下似乎都不起作用:

jq 'map(del (._children))'
jq 'map(if has("_children") then del (._children) end)'
jq 'del(._children)'
jq 'del(.[]._children)'
jq 'del(.[]|._children)'

我不断收到类似于以下内容的错误:

jq: error (at <stdin>:1): Cannot index string with string "_children"

【问题讨论】:

  • 请提供可用作输入的完整 JSON 样本。
  • @chepner 我所拥有的对于我的用例来说已经绰绰有余了。
  • @Qix - 没有看到更多的输入,很难查明您报告的错误的原因。

标签: json object key jq


【解决方案1】:

从拥有它的所有对象中排除 _children 属性

如果你的 jq 有 walk/1 那么你可以:

walk( if type == "object" then del(._children) else . end )

如果不是,首先包括它的 jq 定义(易于 googleable),例如在 ~/.jq

所有以 _ 开头的属性呢?

为此,您也可以使用walk/1。为了清晰和可维护性,定义一个辅助函数是有意义的:

def deleteall(f): with_entries(select(.key | f | not ));

你会调用它:deleteall(startswith("_"))

【讨论】:

  • 整洁 :) 谢谢!
猜你喜欢
  • 2022-11-30
  • 1970-01-01
  • 2017-11-23
  • 2018-03-04
  • 2019-05-20
  • 2010-12-04
  • 2014-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多