json jq -如何过滤内部数组中的值而不知道键

5n0oy7gb  于 2023-11-20  发布在  其他
关注(0)|答案(2)|浏览(86)

下面是JSON:

{
  "ids": {
    "sda": [
      "scsi-0QEMU_QEMU_HARDDISK_drive-scsi2"
    ],
    "sdb": [
      "scsi-0QEMU_QEMU_HARDDISK_drive-scsi0"
    ],
    "sdb1": [
      "lvm-pv-uuid-lvld3A-oA4k-hC19-DXzv-D0Fq-xyME-BwgJid",
      "scsi-0QEMU_QEMU_HARDDISK_drive-scsi0-part1"
    ],
    "sdc": [
      "lvm-pv-uuid-pWes2W-dgYF-l8hG-La48-9ozH-hPdU-MOkOtf",
      "scsi-0QEMU_QEMU_HARDDISK_drive-scsi1"
    ]
  }
}

字符串
我想实现的是在内部数组的值中搜索.*scsi0$,并得到sdb作为结果。

c2e8gylq

c2e8gylq1#

使用JSON jqendswith过滤结果:

.ids | to_entries[] | select(.value[] | endswith("scsi0")) | .key

字符串
结果:

"sdb"


点击这里:https://jqplay.org/s/DAhKosXXgiA
让我们打破它下来...
首先获取.ids,它返回:

{
  "sda": [
    "scsi-0QEMU_QEMU_HARDDISK_drive-scsi2"
  ],
  "sdb": [
    "scsi-0QEMU_QEMU_HARDDISK_drive-scsi0"
  ],
  "sdb1": [
    "lvm-pv-uuid-lvld3A-oA4k-hC19-DXzv-D0Fq-xyME-BwgJid",
    "scsi-0QEMU_QEMU_HARDDISK_drive-scsi0-part1"
  ],
  "sdc": [
    "lvm-pv-uuid-pWes2W-dgYF-l8hG-La48-9ozH-hPdU-MOkOtf",
    "scsi-0QEMU_QEMU_HARDDISK_drive-scsi1"
  ]
}


.然后将结果传递给to_entries函数,将其转换为{key, value}对象数组。
.ids | to_entries返回:

[
  {
    "key": "sda",
    "value": [
      "scsi-0QEMU_QEMU_HARDDISK_drive-scsi2"
    ]
  },
  {
    "key": "sdb",
    "value": [
      "scsi-0QEMU_QEMU_HARDDISK_drive-scsi0"
    ]
  },
  {
    "key": "sdb1",
    "value": [
      "lvm-pv-uuid-lvld3A-oA4k-hC19-DXzv-D0Fq-xyME-BwgJid",
      "scsi-0QEMU_QEMU_HARDDISK_drive-scsi0-part1"
    ]
  },
  {
    "key": "sdc",
    "value": [
      "lvm-pv-uuid-pWes2W-dgYF-l8hG-La48-9ozH-hPdU-MOkOtf",
      "scsi-0QEMU_QEMU_HARDDISK_drive-scsi1"
    ]
  }
]


. next stream使用迭代器运算符.[]来处理对象列表。
.ids | to_entries[]返回:

{
  "key": "sda",
  "value": [
    "scsi-0QEMU_QEMU_HARDDISK_drive-scsi2"
  ]
}
{
  "key": "sdb",
  "value": [
    "scsi-0QEMU_QEMU_HARDDISK_drive-scsi0"
  ]
}
{
  "key": "sdb1",
  "value": [
    "lvm-pv-uuid-lvld3A-oA4k-hC19-DXzv-D0Fq-xyME-BwgJid",
    "scsi-0QEMU_QEMU_HARDDISK_drive-scsi0-part1"
  ]
}
{
  "key": "sdc",
  "value": [
    "lvm-pv-uuid-pWes2W-dgYF-l8hG-La48-9ozH-hPdU-MOkOtf",
    "scsi-0QEMU_QEMU_HARDDISK_drive-scsi1"
  ]
}


.并从值流中选择,.ids | to_entries[] | select(.value[]),其中值以“scsi0”结束,select(.value[] | endswith("scsi0"))

{
  "key": "sdb",
  "value": [
    "scsi-0QEMU_QEMU_HARDDISK_drive-scsi0"
  ]
}


最后,得到键值。
.ids | to_entries[] | select(.value[] | endswith("scsi0")) | .key返回:

"sdb"


命令行:

jq '.ids | to_entries[] | select(.value[] | endswith("scsi0")) | .key'


点击这里:https://jqplay.org/s/DAhKosXXgiA

yqyhoc1h

yqyhoc1h2#

.ids | to_entries[] | select(.value[] | test(".*scsi0$")) | .key

字符串
如果数组中的 any 值与您的正则表达式匹配,则将打印该键。
如果没有匹配,则不会有输出。
to_entries用于轻松捕获对象的密钥。
select过滤值
.value[] | test(".*scsi0$")检查regex的每个值
.key,我们给出结果的关键字

Try it online

相关问题