在JQ中创建新对象时使用IF THEN语句报错,寻求解决方案
问题排查与解决
你的JQ语法本身没有问题,报错的根源是Unix Shell的引号解析冲突——Shell会优先解析命令行中的双引号,导致JQ实际接收到的脚本被截断,触发编译错误。
解决方法
方法1:用单引号包裹整个JQ脚本
这是最简便的方式,Shell会将单引号内的内容原封不动传递给JQ,避免双引号被提前解析:
jq '.customer | {"company": .companyName, "email": .email, "phone": .phone, "type": if .customerType.name == "A" then "SOHO" else "Other" end}' input.json
方法2:转义脚本内的所有双引号
如果必须使用双引号包裹整个脚本,需要对脚本内的每一个双引号添加反斜杠转义:
jq ".customer | {\"company\": .companyName, \"email\": .email, \"phone\": .phone, \"type\": if .customerType.name == \"A\" then \"SOHO\" else \"Other\" end}" input.json
方法3:将脚本保存为文件调用
把JQ逻辑写入单独的文件(比如customer-transform.jq),彻底避免命令行引号问题:
# customer-transform.jq .customer | { "company": .companyName, "email": .email, "phone": .phone, "type": if .customerType.name == "A" then "SOHO" else "Other" end }
运行时通过-f参数指定脚本文件:
jq -f customer-transform.jq input.json
错误原因说明
当你在Shell中直接输入带双引号的JQ命令时,Shell会把"type": if .customerType.name ==后的"A"识别为新的字符串起始标记,导致JQ接收到的脚本被拆分、截断,自然出现unexpected if的语法错误。通过单引号包裹或转义双引号,能确保JQ拿到完整、正确的脚本内容。
内容的提问来源于stack exchange,提问作者g_m
相关产品推荐
相关产品推荐

