【问题标题】:jq select error: "Cannot index string with string <object>"jq 选择错误:“无法使用字符串 <object> 索引字符串”
【发布时间】:2019-04-13 04:30:34
【问题描述】:

命令:

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

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

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

a

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

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

"someotherobj": "123"

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

我真正想要的是能够搜索在input 下至少有一对"$link": "randomtext1" 的任何条目。是否有更模糊的搜索功能可以让我实现这一目标?

我尝试使用两个contains,希望它能通过管道传递信息:

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

但它根本不喜欢那样..

test.json 文件:

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

【问题讨论】:

    标签: json jq


    【解决方案1】:

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

    这里的关键词,无论是问题还是下面的答案,都是any

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

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

    【讨论】:

    • 谢谢@peak。该命令适用于示例:cat test.json | jq -r '.[] | select( any(.input[]; has("$link") and (.["$link"] | index("randomtext1") ) ) ) | .id' 我不知道是否有一些缓存机制或我的计算机。如果我更改 test.txt 文件中的值,出于测试目的,会出现不一致的错误“无法检查字符串是否具有字符串键”:change both "randomtext1" to "randomtext3"
    • ... 或 change the first "randomtext1" to "randomtext3".
    • select( any(.input[]; has("$link") and (.["$link"]=="randomtext1" ) ) ) 相同的问题 如果该命令不满足过滤条件,它似乎只是在第一个条目时出错。我想要的是它显示具有 randomtext1 文本的条目并忽略任何没有的条目。
    • 检查 type=="object" 的更新答案是否符合您的要求?
    • 是的! cat test.json | jq -r '.[] | select( any(.input[]; type=="object" and has("$link") and (.["$link"]=="randomtext1"))) | .id' 谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多