Home > Back-end >  How to filter an array of json with jq in linux?
How to filter an array of json with jq in linux?

Time:08-24

I have the following JSON input:

{
  "paging": {
    "count": 0,
    "total": 0,
    "offset": 0,
    "max": 0
  },
  "executions": [
    {
      "id": 5,
      "href": "https://localhost.com.br",
      "permalink": "https://localhost.com.br",
      "status": "succeeded",
      "project": "PROJETO",
      "executionType": "scheduled",
      "date-started": {
        "unixtime": 1660793400012,
        "date": "2022-08-18T03:30:00Z"
      },
      "date-ended": {
        "unixtime": 1660793409694,
        "date": "2022-08-18T03:30:09Z"
      },
      "job": {
        "id": "cdkwednweoi-8745bjdf-kcjkjr8745",
        "averageDuration": 0,
        "name": "routine",
        "group": "",
        "project": "PROJECT",
        "description": "",
        "href": "https://localhost.com.br",
        "permalink": "https://localhost.com.br"
      },
      "description": "runner",
      "argstring": null,
      "serverUUID": "jdnsdnasldnaje382nf5ubv",
      "successfulNodes": [
        "84jsk937nf"
      ]
    }
  ]
}

First I want to select an array by a property name. And then I want to select an object of the array by the value of the propertyes.

Example of the desired informations on output:

  "href"
  "status"
  "project"

  "date-started": 
   "unixtime": 48298437239847,
   "date": "2022-07-17"

 "date-ended": 
   "unixtime": 48298437239847,
   "date": "2022-07-17"

  "job":
  "name": "cleaner"

I knew how to get the firts values: jq -r '.executions[] | [.href, .status, .project']

But the other ones I don't know how to do, I've tried with: jq '.executions[] | with_entries( select(.value | has("date-started") ) )'

But it doesn't works.

CodePudding user response:

Your first query produces a JSON array, so in this response, I'll assume it will suffice to produce an array of the eight values of interest in the order you've specified.

With your input, the following invocation produces the eight values as shown below:

jq '.executions[]
  | [.href, .status, .project,
     (."date-started" | (.unixtime, .date)),
     (."date-ended" | (.unixtime, .date)),
     .job.name]' 

Output:

[
  "https://localhost.com.br/rundeck/api/40/execution/2340",
  "succeeded",
  "PROJETO",
  1660793400012,
  "2022-08-18T03:30:00Z",
  1660793409694,
  "2022-08-18T03:30:09Z",
  "proc_limpeza_saft"
]
  • Related