jq 中调用自定义模块的格式是什么



我需要使用 jq 对 json 结构中的字符串进行 url 解码。我在~/.jq/urldecode.jq下定义了一个自定义模块,但是在调用它时:

jq '.http.referrer | url_decode::url_decode' file.json

我收到错误消息:

jq: 1 compile error

模块源为:

def url_decode:
  # The helper function converts the input string written in the given
  # "base" to an integer
  def to_i(base):
    explode
    | reverse
    | map(if 65 <= . and . <= 90 then . + 32  else . end)   # downcase
    | map(if . > 96  then . - 87 else . - 48 end)  # "a" ~ 97 => 10 ~ 87
    | reduce .[] as $c
        # base: [power, ans]
        ([1,0]; (.[0] * base) as $b | [$b, .[1] + (.[0] * $c)]) | .[1];
  .  as $in
  | length as $length
  | [0, ""]  # i, answer
  | until ( .[0] >= $length;
      .[0] as $i
      |  if $in[$i:$i+1] == "%"
         then [ $i + 3, .[1] + ([$in[$i+1:$i+3] | to_i(16)] | implode) ]
         else [ $i + 1, .[1] + $in[$i:$i+1] ]
         end)
  | .[1];  # answer

正确的语法是什么?

理论上,通过您的设置,您应该能够按照以下方式调用 jq

jq 'import "urldecode" as url_decode;
  .http.referrer | url_decode::url_decode' file.json

或者更简单地说:

jq 'include "urldecode";
  .http.referrer | url_decode' file.json

然而,在某些情况下,理论并不完全适用。 在这种情况下,jq 1.5 和 1.6 可以使用以下解决方法:

(1) 指定-L $HOME作为命令行参数,并在模块规范中给出相对路径名。 因此,在您的情况下,命令行将如下所示:

jq -L $HOME 'import ".jq/urldecode" as url_decode; ...

或:

jq -L $HOME 'include ".jq/urldecode"; ...

(2) 使用 {搜索: _} 功能,例如

jq 'include "urldecode" {search: "~/.jq"} ; ...' ...
jq 'import "urldecode" as url_decode {search: "~/.jq"} ; ...' ...

默认情况下,JQ 从标有 .jq 文件扩展名的根目录文件中的隐藏文件夹中读取:~/.jq (["~/.jq", "$ORIGIN/../lib/jq", "$ORIGIN/../lib"])

要引用模块,您可以使用导入函数,然后在分号后遵循正常的 jq 命令。下面的"as lib"也允许您更改命名空间的名称:

 jq 'import "urldecode" as lib; .http.referrer | lib::url_decode' file.json

您可以使用 -L 选项覆盖 .jq 文件的存储位置。

我不确定如何在 JQ 中做自定义模块,但如果你使用 bash 我建议为此管道到 PERL。到目前为止,这是我发现的快速 url-en-code/解码 HTML 实体的最简单方法,我通常将其与 JQ 结合使用

echo 'http://domain.tld/?fields=&#123;fieldname_of_type_Tab&#125' | perl -MHTML::Entities -pe 'decode_entities($_)'

解码 URL Unix/Bash 命令行(不带 sed)

最新更新