使用jq检索命令行指定的字段

Ste*_*veT 4 jq

鉴于此输入

{
  "attributes": {
    "f1": "one",
    "f2": "two",
    "f3": "three"
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望能够在 jq 命令行上指定要检索哪些字段并将值吐出在同一行上以空格分隔。

jq -r 'some-filter' --argjson fields '["f3","f1"]' test.json

结果:three one

jq -r 'some-filter' --argjson fields '["f2"]' test.json

结果:two

我尝试过这个过滤器的几种变体,但没有成功

.attributes
 | $fields | . as $f | "\($f)"
Run Code Online (Sandbox Code Playgroud)

ste*_*ver 6

可以使用变量符号绑定(如您尝试的那样)来完成此操作

jq -r --argjson fields '["f3","f1"]' '[$fields[] as $f | .attributes | .[$f]] | join(" ")' test.json
Run Code Online (Sandbox Code Playgroud)

或者稍微紧凑一些

jq -r --argjson fields '["f3","f1"]' '[$fields[] as $f | .attributes[$f]] | join(" ")' test.json
Run Code Online (Sandbox Code Playgroud)

但至少在 jq 1.6 中,您似乎可以将$fields[]迭代器传递给以下形式的通用对象索引.[<string>]

jq -r --argjson fields '["f3","f1"]' '[.attributes[$fields[]]] | join(" ")' test.json
Run Code Online (Sandbox Code Playgroud)

前任。

$ jq -r --argjson fields '["f3","f1"]' '[.attributes[$fields[]]] | join(" ")' test.json
three one
$ jq -r --argjson fields '["f2"]' '[.attributes[$fields[]]] | join(" ")' test.json
two
Run Code Online (Sandbox Code Playgroud)