在JQ中可以从同一个对象执行命令吗?
以下为例
{
"cmd": ".name += \" Smith\" | .name",
"name": "John"
}
如果你看到我有 name 和 cmd 作为两个键。如果您从 JQPlay 中的 cmd 值运行文本。您将看到下面的物体
"John Smith"
是否可以使用单个 JQ 查询来完成?
正如@pmf指出的,jq不提供“eval”函数,所以如果你真的想计算jq表达式,你必须编写自己的,这可能不是你想要的。
但是,还有一个合理的选择。由于您显然愿意在 JSON 中包含某种要求值的表达式,因此您可以利用 jq 对数组路径的支持,并编写一个简单的求值器。例如, 如果您愿意将 JSON 模板编写为:
{
"name": [["firstname"], " Smith"],
"firstname": "John"
}
然后是这一点基础设施:
def ispath:
type == "array" and all(.[]; type | IN("string","number") );
# eval . in the context of $context
def eval($context):
. as $x
| if type == "string" then .
elif ispath then $context | getpath($x)
elif type == "array"
then map( eval($context) ) | add
elif type == "object"
then map_values(eval($context))
else tostring
end;
可以让您基本上实现您想要的目标:
{
"name": [["firstname"], " Smith"],
"firstname": "John"
}
| eval(.)