如何为jq函数添加参数?

时间:2019-10-26 21:27:33

标签: jq

def gather($ary):
  INDEX(.[]; .column) as $dict
  | $ary
  | map( $dict[.] | .value );

.[] | gather(["h1", "h2", "h3"])

鉴于上面的jq文件,我得到以下输出。我想在gather()中添加“ column”和“ value”附加参数,以便用户可以轻松更改它们。您能告诉我如何使标量成为函数参数吗?谢谢。

$ jq -f ./main.jq <<EOF
[
  [
    { "column": "h1", "value": "v1" },
    { "column": "h2", "value": "v2" },
    { "column": "h3", "value": "v3" }
  ],
  [
    { "column": "h1", "value": "v4" },
    { "column": "h2", "value": "v5" },
    { "column": "h3", "value": "v6" }
  ]
]
EOF
[
  "v1",
  "v2",
  "v3"
]
[
  "v4",
  "v5",
  "v6"
]

1 个答案:

答案 0 :(得分:0)

函数参数由;而不是,分隔;还要注意,正如jq manual所说:

  

参数作为过滤器(没有参数的函数)而不是作为值传递...

因此您可以定义:

def gather($ary; column; value):
   ....

并将其调用为:

def gather(["h1", "h2", "h3"]; .column; .value)

另请参阅https://github.com/stedolan/jq/wiki/How-to:-Avoid-Pitfalls#multi-arity-functions-and-commasemi-colon-confusability