【问题标题】:Unable to retrieve key:values, getting error --> jq: error (at <stdin>:0): Cannot index number with string无法检索键:值,出现错误 --> jq: 错误(在 <stdin>:0):无法用字符串索引数字
【发布时间】:2021-01-18 15:17:32
【问题描述】:

无法提取键:值对,尝试索引块。

<nd.com.citrix.netscaler.json" -X GET https://abcd.com/nitro/v1/config/lbpersistentsessions?args=vserver:puppet-vip.ta10.sd | jq '[.[] ] | .[3] | [.srcip]'

得到以下错误:

jq: error (at &lt;stdin&gt;:0): Cannot index array with string "srcip"

我需要将 key:values 提取为 srcip 和destip(见下文)

<ion/vnd.com.citrix.netscaler.json" -X GET https://abcd.com/nitro/v1/config/lbpersistentsessions?args=vserver:somevip | jq '[.[] ] | .[3]' | more
[
  {
    "vserver": "somevip",
    "type": "1",
    "typestring": "SOURCEIP",
    "srcip": “1.1.1.1",
    "srcipv6": "::/0",
    "destip": "2.2.2.2",
    "destipv6": "::/0",
    "flags": false,
    "destport": 0,
    "vservername": “somevip”,
    "timeout": "0",
    "referencecount": "0",
    "persistenceparam": "1.1.1.1"
  },

我不得不使用 [.3] 来索引,因为原始输出是:

<-Type:application/vnd.com.citrix.netscaler.json" -X GET https://abcd.com/nitro/v1/config/lbpersistentsessions?args=vserver:somevip | jq '[.[] ]' | more
[
  0,
  "Done",
  "NONE",
  [
    {
      "vserver": "somevip",
      "type": "1",
      "typestring": "SOURCEIP",
      "srcip": “1.1.1.1”,
      "srcipv6": "::/0",
      "destip": "2.2.2.2",
      "destipv6": "::/0",
      "flags": false,
      "destport": 0,
      "vservername": "somevip",
      "timeout": "0",
      "referencecount": "0",
      "persistenceparam": "1.1.1.1"
    },
    {
      "vserver": "somevip",
      "type": "1",
      "typestring": "SOURCEIP",
      "srcip": "3.3.3.3”,
      "srcipv6": "::/0",
      "destip": "4.4.4.4”,
      "destipv6": "::/0",
      "flags": false,
      "destport": 0,
      "vservername": "somevip",
      "timeout": "0",
      "referencecount": "0",
      "persistenceparam": "1.1.1.1"
    },

另外,尝试这种方式并得到错误:

<GET https://abcd.com/nitro/v1/config/lbpersistentsessions?args=vserver:somevip | jq -r '.[] | select(.vserver == "somevip") | .srcip'

jq: error (at &lt;stdin&gt;:0): Cannot index number with string "vserver"

【问题讨论】:

  • 如果您查看问题中突出显示的语法,您会发现您在两个示例中都使用了错误类型的双引号来包围 srcip 属性。 需要更改为 "。事实上,还有其他几个属性存在同样的问题。我建议做一个查找 + 替换。
  • 这只是一个复制/粘贴错误。我没有使用正确的文本编辑器。我会纠正这个问题。
  • hmm .. 如果我将其输出到 .json 文件和索引,它可以工作。

标签: jq


【解决方案1】:

在解决了 Q 中显示的完整 JSON 的一些小问题后,调用:

jq '.[3][].srcip' input.json

产量:

"1.1.1.1"
"3.3.3.3"

注意事项

  1. .[3][].scrip 只是以下形式的缩写:.[3] | .[] | .srcip

  2. 在您的初始查询中,[.[]] 实际上什么都不做,因为输入是一个数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2020-01-06
    相关资源
    最近更新 更多