【问题标题】:What is the format in jq for calling a custom module?jq中调用自定义模块的格式是什么?
【发布时间】:2019-05-25 00:46:44
【问题描述】:

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

正确的语法是什么?

【问题讨论】:

    标签: module include require jq decodeuricomponent


    【解决方案1】:

    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 文件的存储位置。

    【讨论】:

    • 不幸的是,jq 1.5 和 1.6 中存在一个错误,因此这种理论上有效的方法并不总是有效。请参阅本页其他地方的解决方法。
    【解决方案2】:

    理论上,通过您的设置,您应该能够按照以下方式调用 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"} ; ...' ...
    

    【讨论】:

    • 什么是错误/您指的是什么情况?你在jq 1.5 上发布的所有排列都不适合我
    • @Huckle - 由于 Q 将模块文件名指定为 urldecode.jq 我已经相应地更新了答案。
    【解决方案3】:

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

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

    Decode URL Unix/Bash Command Line (without sed)

    【讨论】:

      猜你喜欢
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      相关资源
      最近更新 更多