在JSON查询中获取父元素引用

mfpqipee  于 2023-06-07  发布在  其他
关注(0)|答案(2)|浏览(164)

下面是JSON:

{
  "virtual_machines": [
    {
      "guest_name": "guest1",
      "mac_address": [
        "00:01:02:03:04:05"
      ],
      "vm_network": {
        "00:01:02:03:04:05": {
          "ipv4": [
            "192.168.2.23"
          ],
          "ipv6": [
            "fe80::896:2e12:c059:4237"
          ]
        },
        "c2:e3:7c:ac:60:c5": {
          "ipv4": [
            "10.42.0.0"
          ],
          "ipv6": []
        },
        "5a:00:fb:5e:3d:65": {
          "ipv4": [
            "10.42.0.1"
          ],
          "ipv6": []
        }
      }
    },
    {
      "guest_name": "guest2",
      "ip_address": "172.20.8.34",
      "mac_address": [
        "10:11:12:13:14:15",
        "30:31:32:33:34:35"
      ],
      "vm_network": {
        "10:11:12:13:14:15": {
          "ipv4": [
            "172.20.8.34"
          ],
          "ipv6": []
        },
        "30:31:32:33:34:35": {
          "ipv4": [
            "172.16.172.34",
            "172.16.172.30"
          ],
          "ipv6": [
            "fe80::ad7f:c2:f621:e718"
          ]
        }
      }
    }
  ]
}

从这个JSON中,我需要从vm_network[]中获取所有在mac_address[]处有条目的ipv4,并将其打印为$guest_name,$mac_address,$ipv4
我能得到的最好的是guest_name后跟ipv4,但我找不到一种方法来获得该ipv4的mac_address:

jq -r  '.virtual_machines[] | .guest_name  + ","+ (.vm_network[.mac_address[]] |.ipv4[])' < json_file
guest1,192.168.2.23
guest2,172.20.8.34
guest2,172.16.172.34
guest2,172.16.172.30

我需要的输出是:

guest1,00:01:02:03:04:05,192.168.2.23
guest2,10:11:12:13:14:15,172.20.8.34
guest2,30:31:32:33:34:35,172.16.172.34
guest2,30:31:32:33:34:35,172.16.172.30

有人能帮我完成吗?请不要说vm_network[]中的MAC密钥比mac_address[]中的多,我只对那些在mac_address[]中有匹配条目的MAC密钥感兴趣。

vu8f3i0k

vu8f3i0k1#

将值绑定到变量,以便以后可以重用它们:

.virtual_machines[] | .guest_name as $g | .mac_address[] as $m
| .vm_network[$m].ipv4[] | [$g, $m, .] | join(",")
guest1,00:01:02:03:04:05,192.168.2.23
guest2,10:11:12:13:14:15,172.20.8.34
guest2,30:31:32:33:34:35,172.16.172.34
guest2,30:31:32:33:34:35,172.16.172.30

Demo

exdqitrt

exdqitrt2#

不使用变量的解决方案:

.virtual_machines
| map(
  { guest_name, mac_address: .mac_address[], ipv4: .vm_network | map_values(.ipv4) }
  | { guest_name, mac_address, ipv4: (.ipv4[.mac_address] // [])[] }
)
| .[]
| join(",")

检查online

相关问题