Skip to content

Instantly share code, notes, and snippets.

@bitmvr
Last active January 7, 2024 15:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitmvr/10a2b24ea7b25bc3f3e999b5472e084c to your computer and use it in GitHub Desktop.
Save bitmvr/10a2b24ea7b25bc3f3e999b5472e084c to your computer and use it in GitHub Desktop.
Create Parseable cURL Response with Bash and jq
#!/usr/bin/env bash
__http_request_example(){
curl \
--silent \
--location http://ip.jsontest.com \
--write-out "\n%{http_code}"
}
__response_formatter(){
response="$1"
echo '{}' | jq \
--arg body "$(sed \$d <<< "$response")" \
--arg status_code "$(tail -n1 <<< "$response")" \
'.body=$body|.status_code=$status_code'
}
response="$(__http_request_example)"
response_to_json="$(__response_formatter "$response")"
echo "-----------------------------------------------------"
echo "Request Body"
echo "-----------------------------------------------------"
echo "$response_to_json" | jq --raw-output '.body'
echo "-----------------------------------------------------"
echo "Request Status Code"
echo "-----------------------------------------------------"
echo "$response_to_json" | jq --raw-output '.status_code'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment