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

如何提取JSON中动态根节点及对应属性并格式化输出?

提取JSON动态键及对应属性并格式化输出

问题背景

现有test.json文件包含如下JSON数据:

{
       "result_set": {
        "/api/device/4756": {
            "name": "Arbitrator",
            "ip": "127.0.0.1",
            "hostname": "acme.arbitrate.com"
        },
        "/api/device/4757": {
            "name": "Auditor",
            "ip": "127.0.0.2",
            "hostname": "acme.auditor.com"
        },
        "/api/device/4758": {
            "name": "Augumentor",
            "ip": "127.0.0.3",
            "hostname": "acme.augumentor.com"
        }
    }
}

需要提取result_set下的动态键(如/api/device/4756)及其对应子节点的name、ip、hostname属性,按每行逗号分隔的格式输出,预期结果:

/api/device/4756, Arbitrator, 127.0.0.1, acme.arbitrate.com
/api/device/4757, Auditor, 127.0.0.2, acme.auditor.com
/api/device/4758, Augumentor, 127.0.0.3, acme.augumentor.com

原命令cat test.json | jq -r '["names"], (.result_set | [])'无法得到预期结果,因为它仅提取了result_set的值,没有包含动态键,且输出格式不符合要求。

解决方法

使用jq的to_entries函数将对象转换为键值对数组,再提取所需字段并格式化:

cat test.json | jq -r '.result_set | to_entries[] | [.key, .value.name, .value.ip, .value.hostname] | join(", ")'

命令解释

  • .result_set | to_entries[]:将result_set对象转换为键值对数组,每个元素包含key(动态路径)和value(对应属性对象)。
  • [.key, .value.name, .value.ip, .value.hostname]:将需要的字段组合成数组。
  • join(", "):将数组元素用逗号加空格连接成字符串,-r参数确保输出原始字符串而非JSON格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 09:05:14