mrk
mrk

Reputation: 730

How to print specific object keys using jq?

I want to do a really simple thing using jq and I can't.

The object is:

{
  "DomainStatus": {
    "DomainId": "12345",
    "DomainName": "test",
    "ARN": "arn:aws:es:eu-west-1:12345:domain/test",
    "Created": true,
    "Deleted": false,
    "Endpoint": "test.com",
    "Processing": false,
    "UpgradeProcessing": false,
    "ElasticsearchVersion": "5.3",
    "ElasticsearchClusterConfig": {
      "InstanceType": "t2.medium.elasticsearch",
      "InstanceCount": 2,
      "DedicatedMasterEnabled": false,
      "ZoneAwarenessEnabled": true,
      "ZoneAwarenessConfig": {
        "AvailabilityZoneCount": 2
      }
    },
    "EBSOptions": {
      "EBSEnabled": true,
      "VolumeType": "gp2",
      "VolumeSize": 30
    },
... more fields ...
  }
}

And I want any of these options:

Option 1:

{
  "DomainName": "test",
  "Endpoint": "test.com",
  "ElasticsearchClusterConfig": {
    "InstanceType": "t2.medium.elasticsearch",
    "InstanceCount": 2,
  }
}

OR

Option 2:

{
  "DomainName": "test",
  "Endpoint": "test.com",
  "InstanceType": "t2.medium.elasticsearch",
  "InstanceCount": 2,
}

I achieved Option 2 using:

jq '.DomainStatus | {DomainName, Endpoint, InstanceType: .ElasticsearchClusterConfig.InstanceType, InstanceCount: .ElasticsearchClusterConfig.InstanceCount}'

BUT the problem is that I don't want to write redundant code.

I don't want this line: InstanceType: .ElasticsearchClusterConfig.InstanceType

It want something like this: .ElasticsearchClusterConfig | {InstanceType, InstanceCount} inside the jq command I wrote before.

Upvotes: 2

Views: 330

Answers (1)

Inian
Inian

Reputation: 85530

You don't have to repeat any code. You can instruct jq to keep only the fields you want. The |=, assignment update operator modifies the object to its left, by recreating it with fields on its right. In our case, only update the ones you need.

.DomainStatus | { 
    DomainName, 
    Endpoint, 
    ElasticsearchClusterConfig: (
       .ElasticsearchClusterConfig | { 
           InstanceType, 
           InstanceCount 
       }
    )
}

option 1 - jq play

or option 2, if you don't want to type out the names explicitly, use a placeholder like

.DomainStatus | .ElasticsearchClusterConfig as $ec | { 
    DomainName, 
    Endpoint, 
    InstanceType:  $ec.InstanceType, 
    InstanceCount: $ec.InstanceCount
}

option 2 - jq play

Upvotes: 3

Related Questions