简体   繁体   中英

Bash: How to pass cookie in JSON format to curl

I am struggling to attach a cookie JSON file to curl request in bash.

I know it can be done with cookie.txt but since I have it in the following pattern:

{"provisioning": "61d83f29bda251.85229990"}

The curl request:

curl -k -v -b cookie.json -F name=csr -F filedata=@${CSRFILE} https://prov.is.byl.com/cert_signer.php >${CRTFILE}

Is it possible instead of having to send it this way?:

curl -k -v -b 'provisioning=61d83f29bda251.85229990' -F name=csr -F filedata=@${CSRFILE} https://prov.is.byl.com/cert_signer.php >${CRTFILE}

You could turn your JSON cookies file into the proper string format expected by curl like this:

curl -k -v \
  -b "$(jq -r '[to_entries[]|([.key,.value|@uri]|join("="))]|join(";")' cookie.json)" \
  -F name=csr -F "filedata=@$CSRFILE" \
  https://prov.is.byl.com/cert_signer.php >"$CRTFILE"

The jq command transforms cookie.json into a cookie string in the name=value;name2=value2;...; format as expected by the curl -b option:

jq -r '[to_entries[]|([.key,.value|@uri]|join("="))]|join(";")' cookie.json

Here is the jq script itself:

# start populating an array
[
  # transform input object cookie.json
  # members and value into array entries
  to_entries[] | (
    # Create an array for each entry
    [
      # with object member key to become cookie name
      .key,
      # and value encoded as uri format in case it contains
      # characters not allowed in an HTTP header (like CR, LF, TAB, SPACE, ...)
      .value | @uri
    ] | join("=") # join this array entries with an equal sign
  )
] | join(";") # join array entries of cookie_name=cookie_value with a semocolon

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM