如何使用jq访问嵌套JSON的首个键并获取对应值
问题:访问JSON指定层级的首个键值对
原始JSON数据
{ "query": "rest ec", "elected_facts_mapping": { "AWS": { "ECS": { "attachments": [ "restart_ecs" ], "text": [ "Great!" ] } } }, "top_facts_mapping": { "AWS": { "ECS": { "attachments": [ "restart_ecs" ], "text": [ "Great!" ] }, "EC2": { "attachments": [ "create_ec2" ], "text": [ "Awesome" ] } }, "GitHub": { "Pull": { "attachments": [ "pull_req" ], "text": [ "Be right on it" ] } }, "testtttt": { "test": { "attachments": [ "hello_world" ], "text": [ "Be right on it" ] } }, "fgjgh": { "fnfgj": { "attachments": [ "hello_world" ], "text": [ "Be right on it" ] } }, "tessttertre": { "gfdgfdgfd": { "attachments": [ "hello_world" ], "text": [ "Great!" ] } } }, "elected_facts_with_prefix_text": null }
需求
访问top_facts_mapping下的第一个键(即AWS),以及AWS下的第一个键(即ECS)对应的内容。
尝试过的DSL代码
'.span | fromjson' '.span_data.top_facts_mapping | keys[0]' '.span_data.top_facts_mapping[${top_facts_prepare_top_fact_topic}] | keys[0]' '.top_facts_prepare_top_fact_topic_subtopic[${top_facts_prepare_top_fact_topic}][${top_facts_prepare_top_fact_topic_subtopic}]'
正确的jq实现方式
1. 获取top_facts_mapping的第一个键(AWS)
.top_facts_mapping | keys[0]
2. 获取AWS下的第一个键(ECS)
.top_facts_mapping.AWS | keys[0]
3. 获取ECS对应的完整内容
动态获取(无需硬编码键名):
.top_facts_mapping | .[keys[0]] | .[keys[0]]
硬编码键名(明确知道键名时使用):
.top_facts_mapping.AWS.ECS
4. 一次性输出第一个顶级键、其子键及对应内容
.top_facts_mapping | { 顶级键: keys[0], 子级键: .[keys[0]] | keys[0], 内容: .[keys[0]] | .[keys[0]] }
说明
- jq的
keys函数会返回对象所有键组成的数组,keys[0]即可取数组第一个元素(即首个键)。 - 通过
.[]或.+键名的语法可以访问对象属性,结合keys[0]就能动态获取首个键对应的内容。
内容的提问来源于stack exchange,提问作者SteveS
相关产品推荐
相关产品推荐

