zsh中如何将含变量替换的多行JSON字符串赋值给变量
在zsh中赋值带变量替换的多行JSON字符串的解决方法
问题背景
原本在bash中可正常运行的脚本,将解释器改为zsh后执行报错parse error near \json=$(cat <<EOF'`,原脚本如下:
#!/usr/bin/env bash phone='+1234567890' firstname='Donald' lastname='Trump' birthdate='1946-06-14' json=$(cat <<EOF { "firstname" : "$firstname", "lastname" : "$lastname" , "birthdate" : "$birthdate", "phone" : "$phone" , "department": "d45a7caa-a56c-43c2-be33-7064064856be", "status" : "candidate" } EOF) curl --json "$json" 'https://usa.example.com/president/elect'
可行解决方案
zsh对$(...)与Here Document的组合语法要求更严格,可通过以下几种方式解决:
方法一:简化Here Document的赋值写法
zsh支持直接将Here Document内容通过$(...)赋值,无需额外调用cat,调整后代码如下:
#!/usr/bin/env zsh phone='+1234567890' firstname='Donald' lastname='Trump' birthdate='1946-06-14' json=$(<<EOF { "firstname" : "$firstname", "lastname" : "$lastname" , "birthdate" : "$birthdate", "phone" : "$phone" , "department": "d45a7caa-a56c-43c2-be33-7064064856be", "status" : "candidate" } EOF ) curl --json "$json" 'https://usa.example.com/president/elect'
如果需要用制表符缩进美化代码,可改用<<-EOF(注意仅支持制表符,普通空格无效):
json=$(cat <<-EOF { "firstname" : "$firstname", "lastname" : "$lastname" , "birthdate" : "$birthdate", "phone" : "$phone" , "department": "d45a7caa-a56c-43c2-be33-7064064856be", "status" : "candidate" } EOF )
方法二:直接变量拼接JSON字符串
若JSON结构简单,可直接用字符串拼接赋值,无需Here Document:
json="{ \"firstname\" : \"$firstname\", \"lastname\" : \"$lastname\" , \"birthdate\" : \"$birthdate\", \"phone\" : \"$phone\" , \"department\": \"d45a7caa-a56c-43c2-be33-7064064856be\", \"status\" : \"candidate\" }"
方法三:用专业工具生成JSON(推荐)
为避免手动拼接时的转义错误,建议用jq工具生成JSON,能保证格式正确性:
json=$(jq -n \ --arg fn "$firstname" \ --arg ln "$lastname" \ --arg bd "$birthdate" \ --arg p "$phone" \ '{ firstname: $fn, lastname: $ln, birthdate: $bd, phone: $p, department: "d45a7caa-a56c-43c2-be33-7064064856be", status: "candidate" }' )
内容的提问来源于stack exchange,提问作者danissimo
相关产品推荐
相关产品推荐

