JQ中的括号为.key

Kyl*_*ndt 4 json jq

我不明白为什么要使用密钥()才能工作:

# kbrandt at glade.local in ~ on git:master x [15:08:19]
$ cat host | jq '. | to_entries | map({ (.key) : .value.CPU.PercentUsed })' | tail
  {
    "rpi-b827eb2d7d23": 10.333333333333334
  },
  {
    "rpi-b827eb8d7c8d": 60
  },
  {
    "rpi-b827eba999fa": 40.733333333333334
  }
]

# kbrandt at glade.local in ~ on git:master x [15:08:54]
$ cat host | jq '. | to_entries | map({ .key : .value.CPU.PercentUsed })' | tail
jq: error: syntax error, unexpected FIELD (Unix shell quoting issues?) at <top-level>, line 1:
. | to_entries | map({ .key : .value.CPU.PercentUsed })
jq: 1 compile error
Run Code Online (Sandbox Code Playgroud)

Jef*_*ado 8

定义对象文字时,括号表示表达式值应该是属性名称.否则,如果您没有使用括号,则它是文字名称.

所以这些是用"foo"属性定义对象的等效方法:

{ foo: 1 }
{ "foo": 2 }
"foo" as $name | { ($name): 3 }
{ somename: "foo" } | { (.somename): 4 }
Run Code Online (Sandbox Code Playgroud)