Search code examples
jsonzsh

zsh - How to assign a miltiline json string with substituted values to a variable


I have the script:

#!/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'

which I run in a zsh interactive shell. It works perfectly. Now I change the first line to

#!/usr/bin/env zsh

and it fails with

parse error near `json=$(cat <<EOF'

How can I assign a multiline string value with substitution to a variable in zsh?


Solution

  • The closing ) of the json=$() must be on a seperate line, not after the EOF:


    #!/usr/bin/env zsh
    
    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'
    

    Keep in mind that generating complex JSON structure by hand is asking for issues. You mind want to use a tool like to properly generate JSON.