jq:文件格式为过滤器(-f)与库(-L)


❯ jq --version
jq-1.6

我使用.jq文件作为过滤器,如下所示,它有效:

❯ cat jq/script.jq
def fi(v):
v | tostring |
if test("\.") then
"float"
else
"integer"
end;
def estype(v):
if type=="number" then
fi(v)
else
type
end;
def esprop(v):
if type=="object" then
{"properties":  v | with_entries(.value |= esprop(.))}
else
{"type": estype(v)}
end;
with_entries(.value |= esprop(.))
❯ cat test.json | jq -f jq/script.jq
...(omit results)

但当我把它用作库时,它会抛出一个错误:

# comment the last filter, except the definitions of functions
❯ cat jq/script.jq
def fi(v):
v | tostring |
if test("\.") then
"float"
else
"integer"
end;
def estype(v):
if type=="number" then
fi(v)
else
type
end;
def esprop(v):
if type=="object" then
{"properties":  v | with_entries(.value |= esprop(.))}
else
{"type": estype(v)}
end;
# with_entries(.value |= esprop(.))
❯ cat test.json | jq -L jq/script.jq 'import script;'
jq: error: syntax error, unexpected IDENT, expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
import script;
jq: 1 compile error
  1. 这意味着什么,我如何调试和修复它?

  2. 作为过滤器或库的.jq文件有不同的语法吗(看起来不是这样(?

1a。这是什么意思

语法错误,意外的IDENT,应为FORMAT或QQSTRING_START

这意味着解析器在需要字符串的地方找到了一个标识符。(FORMAT是@csv@text等格式化程序的令牌,而QQSTRING_START是"script"等字符串的令牌。实际上,在这里使用格式化程序是没有用的,因为它不允许您使用非常量字符串,但解析器不知道这一点。(

1b。如何调试和修复此问题

可能最容易参考手册。它说形式期望";导入";是

import RelativePathString as NAME;

以及预期的";包括";是

include RelativePathString;

它缺乏使这一点100%清楚的例子,但是";RelativePathString";是一个占位符,它需要是一个文字字符串。试试其中一个:

cat test.json | jq -L jq 'include "script"; with_entries(.value |= esprop(.))'
cat test.json | jq -L jq 'import "script" as script; with_entries(.value |= script::esprop(.))'

请注意,库路径应该是包含脚本的目录,以及include和import之间的区别。

2.用作过滤器或库的.jq文件有不同的语法吗

它们使用相同的语法。问题出在import语句上,而不是脚本文件上。

最新更新