繁体   English   中英

如何过滤对象数组中的键对(json 和 jq)

[英]How to filter for key pairs in an object array (json and jq)

这是jq 选择错误的后续:“Cannot index string with string <object>”

以前,我可以使用以下命令和过滤器过滤具有目标对象的 json 文件中的条目:

[{
    "input": {
        "obj1": {
            "$link": "randomtext1"
        },
        "id": "a"
    }
}]

jq -r '.[] | select( any(.input[]; type=="object" and has("$link") and (.["$link"]=="randomtext1")))|.id' jq -r '.[] | select( any(.input[]; type=="object" and has("$link") and (.["$link"]=="randomtext1")))|.id'将给出“a”

现在如何过滤键“$link”及其值“randomtext1”是否属于数组?

[{
    "input": {
        "obj1": [{
            "$link": "randomtext1"
        }],
        "id": "a"
    }
}]

(我仍然希望能够找到“a”作为结果)

示例 .json:

[
  {
    "input": {
      "obj1": [{
        "$link": "randomtext1"
      }],
      "obj2": [{
        "$link": "randomtext2"
      }],
      "someotherobj": "123"
    },
    "id": "a"
  },
  {
    "input": {
      "obj3": {
        "$link": "randomtext1"
      },
      "obj4": {
        "$link": "randomtext2"
      }
    },
    "id": "b"
  }
]

我希望找到带有“randomtext1”关键字的 a 和 b,但是在 obj1 和 obj2 被示例 json 文件中的数组括号“屏蔽/屏蔽”之后,只能从前一个案例中找到具有相同过滤器的 b。

只需添加“或”以涵盖新的可能性:

.[]
| select( any(.input[];
              (type=="object" and (has("$link") and (.["$link"]=="randomtext1")))
              or (type=="array" and any(.[];
                                        type == "object" and (has("$link") and (.["$link"]=="randomtext1")))) ))
|.id

......或更可读:

def relevant($txt):
  type == "object" and has("$link") and (.["$link"]==$txt);

.[]
| select( any(.input[];
              relevant("randomtext1")
              or (type=="array" and any(.[]; relevant("randomtext1"))) ))
|.id

作为替代方案,您可以考虑使用基于walk-path的unix实用程序jtc

bash $ <file.json jtc -w'<id>l:<val>v[-1]<input>l[$link]:<randomtext1>' -T'{{val}}'
"a"
"b"
bash $ 

详细说明步行路径( -w ):

- '<id>l:< - 将找到标记为id每个值

- <val>v会将值记忆到命名空间val

- [-1]将找到的条目提升一级(基本上是父母的地址)

- <input>l[$link]:<randomtext1> - 将在给定的Json条目下找到每条记录"$link": "randomtext1"记录下的"input"

如果全部成功,则插值发生在( -T )中并且先前记忆的值被内插。

同样的查询也可以在您之前的帖子中使用您的输入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM