Home > Software design >  I have some JSON but I want to extract data based on a variable using jq
I have some JSON but I want to extract data based on a variable using jq

Time:01-12

I have some JSON data which I want to parse using jq

{{
    "metadata":{
      "name":"run1",
      "uid":"b2c0ce",
      "creationTimestamp":"2021-01-01T01:01:01Z"
    },
    "spec":{
      "arguments":{}
    },
    "status":{
      "phase":"Failed",
      "startedAt":"2021-01-01T01:01:01Z",
      "finishedAt":"2021-01-01T01:01:01Z"
    }
},
{
    "metadata":{
      "name":"run2",
      "uid":"9b0af3",
      "creationTimestamp":"2021-01-01T01:01:01Z"
    },
    "spec":{
      "arguments":{}
    },
    "status":{
      "phase":"Succeeded",
      "startedAt":"2021-01-01T01:01:01Z",
      "finishedAt":"2021-01-01T01:01:01Z"}}}

I have a script that a user will enter a "name" and I want to be able to look for and extract the metadata for the name they entered if it exists. So for example if they enter "run7" I wanted the final output to be:

{"metadata":{
    "name":"run7",
    "uid":"b2c0ce",
    "creationTimestamp":"2021-01-01T01:01:01Z"}

or if possible to just show

"name":"run7",
"uid":"b2c0ce",
"creationTimestamp":"2021-01-01T01:01:01Z"

The closest ive gotten is:

jq -r '.[] | .[] | map({name: .name, uid: .uid, time: .creationTimestamp })'  file.json

but im not sure how I can now search only for a certain name. The way I did it gives this:

{
    "name": "run10",
    "uid": "af7b51f",
    "time": "2021-01-01T01:01:01Z"
  },
  {
    "name": null,
    "uid": null,
    "time": null
  },
  {
    "name": null,
    "uid": null,
    "time": null
  } 

I also dont want it to check the "spec" or "status" because thats where the null came from

CodePudding user response:

Assuming those input objects are in an array,

.[] | select(.metadata.name == "run2") | .metadata

Will select the object where .metadata.name === run2.

Then it shows the .metadata of that object so the output becomes:

{
  "name": "run2",
  "uid": "9b0af3",
  "creationTimestamp": "2021-01-01T01:01:01Z"
}

Demo

  •  Tags:  
  • Related