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

如何用JQ从指定JSON文件中提取"hw-name"字段?

解决jq提取带连字符字段的问题

我来帮你搞定这个jq提取的问题!你的命令有两个关键问题需要修正,我们一步步来理清:

问题分析

  1. 第一个命令里的 .comment[] 是错误的——comment 是一个对象(键值对结构),不是数组,不能用 [] 来遍历它的键,直接用 .comment.site-ops-updates 就能定位到目标数组。
  2. 第二个命令已经接近正确,但 hw-name 包含连字符,jq会把它误解析成 hw 减去 name 的表达式,而不是字段名。对于带特殊字符(比如连字符、空格)的字段,必须用引号包裹起来才能正确识别。

正确的jq命令

你可以用以下两种写法中的任意一种:

写法1:用双引号直接包裹字段名

cat json_file.json | jq -r '.comment.site-ops-updates[]."hw-name"'

写法2:用方括号+引号的形式

cat json_file.json | jq -r '.comment.site-ops-updates[].["hw-name"]'

效果验证

假设你的JSON文件内容是:

{ "comment": { "vm-updates": [], "site-ops-updates": [ { "comment": { "message": "You can start maintenance on this resource" }, "hw-name": "Machine has got missing disks. " } ] }, "object_name": "4QXH862", "has_problems": "yes", "tags": "" }

执行上面的命令后,会输出:

Machine has got missing disks. 

这样就能正确提取到hw-name字段的值啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:46:38