首页 > 解决方案 > 在 shell 脚本中提取 json 有效负载

问题描述

我有一个像下面这样的文件。如您所见,花括号之间的行/内容很少。由于有多组打开和关闭的花括号,我想分别获取每行的花括号( { 和 } )之间的内容。

示例文件:

{
   "/tmp/©ƒ-4bf57ed2-velero/velero/templates/crds.yaml": [
   ],
   "/tmp/velero-4bf57ed2-velero/velero/templates/deployment.yaml": [
   ],
   "/tmp/velero-4bf57ed2-velero/velero/templates/restic-daemonset.yaml": [
   ],
   "/tmp/velero-4bf57ed2-velero/velero/templates/secret.yaml": [
   ]
 }
 {
   "/tmp/autoscaler-fb12fa7a-cluster-autoscaler/cluster-autoscaler/templates/deployment.yaml": [
     ".spec.replicas: '2' != '0'",
   ],
   "/tmp/autoscaler-fb12fa7a-cluster-autoscaler/cluster-autoscaler/templates/servicemonitor.yaml": [
     "error: the server doesn't have a resource type \"ServiceMonitor\"\n"
   ]
 }
 {
   "/tmp/metrics-server-1960953a-metrics-server-certs/raw/templates/resources.yaml": [
     "error: the server doesn't have a resource type \"Issuer\"\n",
     "error: the server doesn't have a resource type \"Certificate\"\n"
   ]
 }

预期结果:需要花括号之间的 3 个单独的数据块。

有人可以在这里帮助我吗?

标签: shell

解决方案


感谢您的建议,上面的 jq 不适用于所有 json payload 。例如,对于下面的 json 有效负载,它给出了一个错误

 {
   "/tmp/ingress-dae7bd30-ingress-internet/nginx-ingress/templates/controller-deployment.yaml": [
     ".spec.replicas: '2' != '3'",
   ],
   "/tmp/ingress-dae7bd30-ingress-internet/nginx-ingress/templates/controller-metrics-service.yaml": [
     ".spec.clusterIP: '' != '10.3.24.53'"
   ],
   "/tmp/ingress-dae7bd30-ingress-internet/nginx-ingress/templates/controller-service.yaml": [
     ".spec.clusterIP: '' != '10.3.115.118'"
   ],
   "/tmp/ingress-dae7bd30-ingress-internet/nginx-ingress/templates/controller-stats-service.yaml": [
     ".spec.clusterIP: '' != '10.3.115.30'"
   ],
   "/tmp/ingress-dae7bd30-ingress-internet/nginx-ingress/templates/default-backend-deployment.yaml": [
   ]
 }

推荐阅读