You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在jq中将函数输出存储到变量中?

解决jq中函数结果存储到变量/对象字段的问题

核心错误分析

  • 直接写days: months返回null:jq中引用当前对象的字段必须用.months,裸写months会被视为未定义变量,因此返回null。
  • days: .months|Months_to_Days触发语法错误:在jq的对象构造器{}中,字段值里的管道操作需要用括号包裹,否则解析器会误判语法结构。

正确实现方式

1. 构造包含days字段的对象

将管道表达式用括号包裹,确保jq正确解析:

# 先修正并定义函数(原函数开头的eif改为if,移除调试用的debug)
def Months_to_Days:
  if .|tonumber > 8 then
    ((.|tonumber - 1) * 30) + ((.|tonumber - 1)/2) + 1 - 2|floor
  else
    if .|tonumber < 3 then
      ((.|tonumber - 1) * 30) + (.|tonumber/2)| floor
    else
      ((.|tonumber - 1) * 30) + (.|tonumber/2) - 2| floor
    end
  end;

# 生成包含计算后天数的对象
{
  months: "12",
  days: (.months | Months_to_Days)
}

2. 存储到jq变量供后续函数使用

如果需要将结果绑定到变量重复使用,可以通过管道赋值实现:

def Months_to_Days:
  if .|tonumber > 8 then
    ((.|tonumber - 1) * 30) + ((.|tonumber - 1)/2) + 1 - 2|floor
  else
    if .|tonumber < 3 then
      ((.|tonumber - 1) * 30) + (.|tonumber/2)| floor
    else
      ((.|tonumber - 1) * 30) + (.|tonumber/2) - 2| floor
    end
  end;

# 绑定变量并在后续逻辑中调用
{months: "12"}
| .days = (.months | Months_to_Days)
| $calculated_days = .days
# 示例:后续使用变量的逻辑
| {
    input_months: .months,
    total_days: $calculated_days,
    half_days: $calculated_days / 2
  }

内容的提问来源于stack exchange,提问作者Ioannis Apostolopoulos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 02:05:20