Home > other >  apply condition on json file and fetch the value on that key value exists in linux
apply condition on json file and fetch the value on that key value exists in linux

Time:07-13

I have the packages.json file which contains the docker image details, looks like:

  "dependencies": [
{
  "name": "powershell-core",
  "type": "zip",
  "path": "Dependencies",
  "filename": "PowerShell-Core-6.2.3-win-x64.msi"
},
{
"name": "redis",
"type": "docker-image",
"path": "redis:6.0.10-alpine3.12",
"filename": ""
},
{
  "name": "keycloak",
  "type": "docker-image",
  "path": "jboss/keycloak:12.0.1",
  "filename": ""
},
]

The JSON data is semi-structured and all is not the same. Here I am trying to fetch specific data like "path" with condition like if its a "type": "docker-image" under "dependencies" then fetch it.

I have tried something like:

$ jq '.dependencies[2].path' packages.json

output:

"redis:6.0.10-alpine3.12"

So how to fetch all the "path" having "type" as "docker-image" under "dependencies" from the packages.json file and keep it in a file.

CodePudding user response:

Use select to filter an array:

jq -r '.dependencies[] | select(.type == "docker-image").path' packages.json

The -r removes the double quotes around the paths.

Use redirection to save the output to a file:

... > output
  • Related