0

I am performing a curl test using shell script where I need to save curl server response into JSON along with CURL Information like time_connect, http_code, etc. I am trying the following code to write output to a JSON

  HOST_ADDR="http://$mynds/"

  do_request(){
       echo $(curl $HOST_ADDR --silent -w "\n{\n
        \"HttpCode\": %{http_code},\n
        \"NumRedirects\":%{num_redirects},\n
        \"NumConnects\":%{num_connects},\n
        \"SizeDownloadInBytes\":%{size_download},\n
        \"SizeHeaderInBytes\":%{size_header},\n
        \"SizeRequestInBytes\":%{size_request},\n
        \"SizeUploadInBytes\":%{size_upload},\n
        \"SpeedUploadBPS\":%{speed_upload},\n
        \"SpeedDownloadBPS\":%{speed_download},\n
        \"TimeAppConnectSec\":%{time_appconnect},\n
        \"TimeConnectSec\":%{time_connect},\n
        \"TimeNamelookupSec\":%{time_namelookup},\n
        \"TimePreTransferSec\":%{time_pretransfer},\n
        \"TimeRedirectSec\":%{time_redirect},\n
        \"TimeStartTransferSec\":%{time_starttransfer},\n
        \"TimeTotalSec\":%{time_total},\n
        \"UrlEffective\":\"%{url_effective}\"
 }" -s)
}

do_request

The simple output I am getting:

{"hostIPAddr":"0.0.0.0","hostname":"vm01","text":"Hello World from 
vm01"}` and `{ "HttpCode": 200, "NumRedirects":0, "NumConnects":1, 
"SizeDownloadInBytes":85, "SizeHeaderInBytes":263, 
"SizeRequestInBytes":99, "SizeUploadInBytes":0, 
"SpeedUploadBPS":0.000, "SpeedDownloadBPS":14.000, 
"TimeAppConnectSec":0.000000, "TimeConnectSec":5.553587, 
"TimeNamelookupSec":5.097553, "TimePreTransferSec":5.553868, 
"TimeRedirectSec":0.000000, "TimeStartTransferSec":5.827584, 
"TimeTotalSec":5.827704, "UrlEffective":"http://dns" }

I am getting two JSON outputs one for curl information and one from the server. How do I combine these two outputs into a single JSON variable? Please help.

TBA
  • 1,921
  • 4
  • 13
  • 26
Bhuneshwer
  • 577
  • 1
  • 9
  • 26
  • You can use `jq` to generate JSON from bash. It is explained in [this thread](https://stackoverflow.com/questions/48470049/build-a-json-string-with-bash-variables). – D-FENS Dec 10 '21 at 07:40
  • Use `jq` also to generate the request, because string interpolation does not quote values correctly. – ceving Dec 10 '21 at 09:49

1 Answers1

0
guid_id=$(uuidgen)
file_1="curlJsonRes_$guid_id.json"
file_2="curlMetaRes_$guid_id.json"

do_request(){
  echo $(curl $HOST_ADDR --silent --output $file_1 -w "\n{\n
         \"HttpCode\": %{http_code},\n
         \"NumRedirects\":%{num_redirects},\n
         \"NumConnects\":%{num_connects},\n
    }")
} > $file_2

do_request
#Merging file outputs
echo $(jq -s '.[0] * .[1]' $file_1 $file_2) > $RESULTS_FILE
rm $file_1
rm $file_2
Bhuneshwer
  • 577
  • 1
  • 9
  • 26