jq选择错误:“无法索引字符串为< object>的字符串" [英] jq select error: "Cannot index string with string <object>"

查看:99
本文介绍了jq选择错误:“无法索引字符串为< object>的字符串"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

命令:

cat test.json | jq -r '.[] | select(.input[] | .["$link"] | contains("randomtext1")) | .id'

我希望同时显示两个条目(ab),因为它们都包含randomtext1

I was expecting to have both entries (a and b) to show up since they both contains randomtext1

相反,我得到了以下输出消息:

Instead, I got the following output message:

a

jq: error (at <stdin>:22): Cannot index string with string "$link"

通过一些挖掘,我了解到该问题很可能是由a条目中的以下对象/值对引起的:

From some digging I understand that the issue is likely caused by the following object/value pair in the a entry:

"someotherobj": "123"

因为它不包含对象$link,并且命令中的过滤器希望在input下的所有对象中看到$link,所以在命令有机会搜索b之前它会出错.项.

because it does not contain the object $link and the filter in the command expects to see $link in all objects under the input so it errors out before the command has a chance to search in the b entry.

我真正想要的是能够搜索在input下具有至少一对"$link": "randomtext1"对的任何条目.是否有一个模糊的搜索功能可以使我做到这一点?

What I really want is to be able to search for any entries that have at least one "$link": "randomtext1" pair under input. Is there a fuzzier search feature allowing me to achieve this?

我尝试使用两个contains希望它可以通过管道传送内容:

I tried to use two contains hoping it will just pipe things through:

jq -r '.[] | select(.input[] | contains(["$link"]) | contains("randomtext1")) | .id'

但是一点都不喜欢.

test.json文件:

the test.json file:

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

推荐答案

我真正想要的是能够搜索在输入下至少具有一对"$ link":"randomtext1"对的任何条目.

What I really want is to be able to search for any entries that have at least one "$link": "randomtext1" pair under input.

问题和以下答案中的关键字都是any:

The key word here, both in the question and the following answer, is any:

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

当然,如果您要求键的值为"randomtext1",则可以编写.["$link"] == "randomtext1".

Of course if you require the key's value to be "randomtext1", you'd write .["$link"] == "randomtext1".

这篇关于jq选择错误:“无法索引字符串为&lt; object&gt;的字符串"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆