JQ: A list with multiple values for one key

Viewed 262

Using jq, I want to get a list of application names, all versions and server name. The list should not contain information about the latest version.

Input:

{
  "software": {
    "app_1": {
      "0.0.1": {
        "properties_1": {
          "lang": "en"
        },
        "server": "vm123-4.domain.com"
      },
      "0.0.2": {
        "properties_2": {
          "arch": "x86"
        },
        "server": "vm123-5.comain.com"
      },
      "latest_version": "0.0.2"
    },
    "app_2": {
      "1.0.1": {
        "properties_2": {
          "arch": "x86"
        },
        "server": "vm333-1.domain.com"
      },
      "latest_version": "1.0.1"
    },
    "app_33": {
      "0.44.1": {
        "properties_1": {
          "lang": "en"
        },
        "properties_2": {
          "arch": "x86"
        },
        "properties_3": {
          "boot": "true"
        },
        "server": "vm888-9.domain.com"
      },
      "1.2.2": {
        "properties_3": {
          "boot": "yes"
        },
        "server": "vm123-4.domain.com"
      },
      "latest_version": "1.2.2"
    }
  }
}

Desired output:

"app_1,  0.0.1,  vm123-4.domain.com"
"app_1,  0.0.2,  vm123-5.comain.com"
"app_2,  1.0.1,  vm333-1.comain.com"
"app_33, 0.44.1, vm888-9.comain.com"
"app_33, 1.2.2,  vm123-4.comain.com"

My request will only list one version of the app, but not all. I do not know how to do this.

.software | to_entries[] | [(.key), (.value | to_entries[] | select(.key | IN("latest_version") | not))] | "\(.[0]) \(.[1].key) \(.[1].value.server)"

My output:

"app_1  0.0.1  vm123-4.domain.com"
"app_2  1.0.1  vm333-1.domain.com"
"app_33 0.44.1 vm888-9.domain.com"
2 Answers
jq -r '.software | to_entries[] | .key as $app | .value | to_entries[] | select((.value | objects)) |  [$app, .key, .value.server] | @csv'
.software | to_entries[] | "\(.key) \(.value | to_entries[] | select(.key != "latest_version") | "\(.key) \(.value.server)")"

Will produce

"app_1 0.0.1 vm123-4.domain.com"
"app_1 0.0.2 vm123-5.comain.com"
"app_2 1.0.1 vm333-1.domain.com"
"app_33 0.44.1 vm888-9.domain.com"
"app_33 1.2.2 vm123-4.domain.com"

As you can test in this online demo.


Using --raw-output with tabs \t, we can create a column like output:

app_1   0.0.1   vm123-4.domain.com
app_1   0.0.2   vm123-5.comain.com
app_2   1.0.1   vm333-1.domain.com
app_33  0.44.1  vm888-9.domain.com
app_33  1.2.2   vm123-4.domain.com

Demo

Related