jq 不适用于带有破折号和数字的标签名称

jq not working on tag name with dashes and numbers

我正在使用 jq 但在我的 json 标签中有“-”使 jq 无法编译。我无法逃避它以使其起作用。这里的命令

    curl -X GET -H "X-AppKey:foo" "foo/v2/_status" | jq '.component-status[]'

我在 jq 的 github 中读到这个 ​​post https://github.com/stedolan/jq/issues/202 但我无法让它工作。

这是 curl 的输出

   {
  "status": "ok",
  "hostname": "0b0b495a46db",
  "component-status": [
   {
     "status-code": 200,
     "component": "Service1",
     "status": "OK"
   },
   {
     "status-code": 200,
     "component": "Service2",
     "status": "OK"
   }
  ]
 }

有什么想法吗?

您需要用方括号和双引号引起来:

jq '."component-status"'

根据您给定的输入 returns:

[
  {
    "status": "OK",
    "component": "Service1",
    "status-code": 200
  },
  {
    "status": "OK",
    "component": "Service2",
    "status-code": 200
  }
]

jq Manual (development) --> Basic filters:

.foo, .foo.bar

The simplest useful filter is .foo. When given a JSON object (aka dictionary or hash) as input, it produces the value at the key “foo”, or null if there’s none present.

If the key contains special characters, you need to surround it with double quotes like this: ."foo$".

来自 github 问题 Cannot select field if field name has dashes:

Currently, that gets parsed as a subtraction. You can always explicitly use strings for when your keys don't fit identifier syntax.

or the commenters to his answers did not work for me (probably because I used PowerShell), however in the answer from github issue 有一个解决方案,它成功了——用 \

转义双引号
jq '.\"component-status\"'