如何提取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
相关产品推荐
相关产品推荐

