json - 使用一些关键字从 JQ 构建 json 路径

标签 json jq

我有一个很深的json。有时,我需要查找包含某个单词的键的 json 路径。

{
    "apiVersion": "v1",
    "kind": "Pod",
    "metadata": {
        "creationTimestamp": "2019-03-28T21:09:42Z",
        "labels": {
            "bu": "finance",
            "env": "prod"
        },
        "name": "auth",
        "namespace": "default",
        "resourceVersion": "2786",
        "selfLink": "/api/v1/namespaces/default/pods/auth",
        "uid": "ce73565a-519d-11e9-bcb7-0242ac110009"
    },
    "spec": {
        "containers": [
            {
                "command": [
                    "sleep",
                    "4800"
                ],
                "image": "busybox",
                "imagePullPolicy": "Always",
                "name": "busybox",
                "resources": {},
                "terminationMessagePath": "/dev/termination-log",
                "terminationMessagePolicy": "File",
                "volumeMounts": [
                    {
                        "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
                        "name": "default-token-dbpcm",
                        "readOnly": true
                    }
                ]
            }
        ],
        "dnsPolicy": "ClusterFirst",
        "nodeName": "node01",
        "priority": 0,
        "restartPolicy": "Always",
        "schedulerName": "default-scheduler",
        "securityContext": {},
        "serviceAccount": "default",
        "serviceAccountName": "default",
        "terminationGracePeriodSeconds": 30,
        "tolerations": [
            {
                "effect": "NoExecute",
                "key": "node.kubernetes.io/not-ready",
                "operator": "Exists",
                "tolerationSeconds": 300
            },
            {
                "effect": "NoExecute",
                "key": "node.kubernetes.io/unreachable",
                "operator": "Exists",
                "tolerationSeconds": 300
            }
        ],
        "volumes": [
            {
                "name": "default-token-dbpcm",
                "secret": {
                    "defaultMode": 420,
                    "secretName": "default-token-dbpcm"
                }
            }
        ]
    },
    "status": {
        "conditions": [
            {
                "lastProbeTime": null,
                "lastTransitionTime": "2019-03-28T21:09:42Z",
                "status": "True",
                "type": "Initialized"
            },
            {
                "lastProbeTime": null,
                "lastTransitionTime": "2019-03-28T21:09:50Z",
                "status": "True",
                "type": "Ready"
            },
            {
                "lastProbeTime": null,
                "lastTransitionTime": null,
                "status": "True",
                "type": "ContainersReady"
            },
            {
                "lastProbeTime": null,
                "lastTransitionTime": "2019-03-28T21:09:42Z",
                "status": "True",
                "type": "PodScheduled"
            }
        ],
        "containerStatuses": [
            {
                "containerID": "docker://b5be8275555ad70939401d658bb4e504b52215b70618ad43c2d0d02c35e1ae27",
                "image": "busybox:latest",
                "imageID": "docker-pullable://busybox@sha256:061ca9704a714ee3e8b80523ec720c64f6209ad3f97c0ff7cb9ec7d19f15149f",
                "lastState": {},
                "name": "busybox",
                "ready": true,
                "restartCount": 0,
                "state": {
                    "running": {
                        "startedAt": "2019-03-28T21:09:49Z"
                    }
                }
            }
        ],
        "hostIP": "172.17.0.37",
        "phase": "Running",
        "podIP": "10.32.0.4",
        "qosClass": "BestEffort",
        "startTime": "2019-03-28T21:09:42Z"
    }
}

目前,如果我需要 podIP,那么我会通过这种方式找到具有搜索关键字的对象,然后构建路径

curl myson | jq "[paths]" | grep "IP" --context=10

有什么好的捷径可以简化这个过程吗?我真正需要的是 - 所有可能具有匹配 key 的路径。

spec.podIP
spec.hostIP

最佳答案

选择 路径在最后一个元素中包含关键字,并使用join(".")生成您想要的输出。

paths
| select(.[-1] | type == "string" and contains("keyword"))
| join(".")
  • .[-1] 返回数组的最后一个元素,
  • type == "string" 是必需的,因为数组索引是数字,并且无法检查数字和字符串是否包含它们。

您可能需要指定-r选项。


正如 @JeffMercado 隐式建议的那样,您可以从命令行设置查询,而无需触摸脚本:

jq -r 'paths
| select(.[-1] | type == "string" and contains($q))
| join(".")' file.json --arg q 'keyword'

关于json - 使用一些关键字从 JQ 构建 json 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55406838/

相关文章:

c# - 在 LINQ 中仅将某些列返回到 JSON

arrays - MongoDB - 计算嵌套数组的平均值

json - jq 转换 - json 子数组到分隔字符串

arrays - jq 查找值为包含特定元素的数组的键

json - 使用 jq 合并两个文件

php - 如何在 PHP 中将 HTML 字符串存储在 JSON 中?

java - 如何在 Android API 级别 22 上通过 POST 请求发送 JSON raw

json - 使用 JQ 将 Geojson 附加到 json 字段

json - 嵌套数组,使用 JQ 组合多个过滤器

c# - Linq groupby 列表匹配和计数