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

如何从给定JSON生成所有唯一键路径?求助修正jq命令

生成JSON所有唯一键路径的jq命令修正

需求说明

需要从给定JSON数据中生成所有唯一键路径的列表,每条路径单独占一行。

示例输入JSON

{
   "results":[
      {
         "id":306,
         "name":"First Company",
         "branches":[
            {
               "id":4191,
               "city":"San Francisco",
               "customers":[
                  {
                     "id":446,
                     "name":"Big Tech 1"
                  },
                  {
                     "id":447,
                     "name":"Big Tech 2"
                  }
               ]
            },
            {
               "id":4192,
               "city":"Miami",
               "customers":[
                  {
                     "id":448,
                     "name":"Insurance Tech 1"
                  },
                  {
                     "id":449,
                     "name":"Health Tech 2"
                  }
               ]
            }
         ]
      }
   ]
}

期望输出

results
results.id
results.name
results.branches
results.branches.id
results.branches.city
results.branches.customers
results.branches.customers.id
results.branches.customers.name

问题

尝试了以下jq命令,但无法正常运行:

jq '
def path(k):
  if k | type == "object":
    reduce(.keys[] | path(.), k)
  else:
    [k]
;

.[] | path(".") | flatten | sort' example.json

解决方案

使用jq内置的paths函数结合去重、格式化逻辑,即可实现需求,修正后的命令如下:

jq -r 'paths | map(tostring) | join(".") | select(test("^\\d+$") | not) | unique | .[]' example.json

命令解释

  1. paths:遍历JSON所有节点,生成每个节点的路径数组(例如["results",0,"id"])
  2. map(tostring):将路径数组中的所有元素转为字符串
  3. join("."):用.拼接路径数组,生成完整路径字符串(例如results.0.id)
  4. select(test("^\\d+$") | not):过滤掉纯数字的数组索引,只保留键名组成的路径
  5. unique:对路径列表去重,确保每条路径唯一
  6. .[]:将路径数组展开为单行一个元素的格式
  7. -r:输出原始字符串,避免JSON格式的引号包裹

你之前自定义的path函数逻辑有误,未正确处理数组结构与递归遍历,使用内置的paths函数能更可靠地完成遍历任务。

内容的提问来源于stack exchange,提问作者Denio Mariz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:52:16