2

我需要使用 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

什么是正确的语法?

4

3 回答 3

0

理论上,通过您的设置,您应该能够按照以下方式调用 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) 使用 {search: _} 功能,例如

jq 'include "urldecode" {search: "~/.jq"} ; ...' ...
jq 'import "urldecode" as url_decode {search: "~/.jq"} ; ...' ...
于 2018-12-27T00:57:34.363 回答
0

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

要引用该模块,您可以使用 import 函数,然后在分号后执行正常的 jq 命令。下面的“as lib”还允许您更改命名空间的名称:

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

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

于 2018-12-26T21:34:48.453 回答
-2

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

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

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

于 2018-12-26T23:24:57.760 回答