如何使用jq打印指定对象键?优化冗余代码实现目标输出
Problem
I'm working with AWS Elasticsearch domain JSON data and already have a working jq command to get my desired Option 2 output, but it's redundant because I keep repeating the .ElasticsearchClusterConfig path. I want to streamline this using a cleaner syntax like .ElasticsearchClusterConfig | {InstanceType, InstanceCount} instead.
Here's the simplified structure of my input JSON:
{ "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 } } }
My current working (but redundant) command for Option 2:
jq '.DomainStatus | {DomainName, Endpoint, InstanceType: .ElasticsearchClusterConfig.InstanceType, InstanceCount: .ElasticsearchClusterConfig.InstanceCount}'
This gives me:
{ "DomainName": "test", "Endpoint": "test.com", "InstanceType": "t2.medium.elasticsearch", "InstanceCount": 2 }
Solution
You can use jq's object merge operator (+) to combine two separate objects—one with your top-level fields, and another with the extracted cluster config fields—without repeating the path reference.
Optimized Command for Option 2
jq '.DomainStatus | {DomainName, Endpoint} + (.ElasticsearchClusterConfig | {InstanceType, InstanceCount})'
Breakdown of how this works:
- First, we create an object with just
DomainNameandEndpointdirectly from.DomainStatus - Next, we extract
InstanceTypeandInstanceCountfrom.ElasticsearchClusterConfiginto a second object - The
+operator merges these two objects into a single one, giving you exactly the flat structure you want for Option 2
Bonus: Command for Option 1 (Nested Cluster Config)
If you ever need to go back to Option 1's nested structure, you can cleanly nest the extracted cluster fields like this:
jq '.DomainStatus | {DomainName, Endpoint, ElasticsearchClusterConfig: (.ElasticsearchClusterConfig | {InstanceType, InstanceCount})}'
This keeps your code concise, readable, and free of redundant path references.
内容的提问来源于stack exchange,提问作者mrk

