You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jq打印指定对象键?优化冗余代码实现目标输出

Optimize jq Command to Eliminate Redundant Path References

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:

  1. First, we create an object with just DomainName and Endpoint directly from .DomainStatus
  2. Next, we extract InstanceType and InstanceCount from .ElasticsearchClusterConfig into a second object
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 09:07:32