Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing and storing the json output of a curl command in bash

Tags:

bash

curl

jq

I have five cURL statements that work fine by themselves and am trying to put them together in a bash script. Each cURL statement relies on a variable generated from a cuRL statement executed before it. I'm trying to figure out the smartest way to go about this. Here is the first cURL statement;

curl -i -k -b sessionid -X POST https://base/resource -H "Content-Type: application/json" -H "Authorization: Authorization: PS-Auth key=keyString; runas=userName; pwd=[password]" -d "{\"AssetName\":\"apiTest\",\"DnsName\":\"apiTest\",\"DomainName\":\"domainNameString\",\"IPAddress\":\"ipAddressHere\",\"AssetType\":\"apiTest\"}"

This works fine, it produces this output;

{"WorkgroupID":1,"AssetID":57,"AssetName":"apiTest","AssetType":"apiTest","DnsName":"apiTest","DomainName":"domainNameString","IPAddress":"ipAddressHere","MacAddress":null,"OperatingSystem":null,"LastUpdateDate":"2017-10-30T15:18:05.67-07:00"}

However, in the next cURL statement, I need to use the integer from AssetID in order to execute it. In short, how can I take the AssetID value and store it to a variable to be used in the next statement? In total, I'll be using 5 cURL statements and they rely on values generated in the preceeding statement to execute. Any insight on how is appreciated.

like image 728
Kimomaru Avatar asked Oct 30 '17 15:10

Kimomaru


People also ask

How do I get Curl response in JSON format?

To get JSON with Curl, you need to make an HTTP GET request and provide the Accept: application/json request header. The application/json request header is passed to the server with the curl -H command-line option and tells the server that the client is expecting JSON in response.

How do I write a Curl output to a file?

For those of you want to copy the cURL output in the clipboard instead of outputting to a file, you can use pbcopy by using the pipe | after the cURL command. Example: curl https://www.google.com/robots.txt | pbcopy . This will copy all the content from the given URL to your clipboard.


1 Answers

Download and install jq which is like sed for JSON data. You can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep does for unstructured data. Remember to replace '...' with your actual curl arguments

curl '...' | jq --raw-output '.AssetID'

and to store it in a variable use command-substitution syntax to run the command and return the result.

asset_ID=$( curl '...' | jq --raw-output '.AssetID' )

In the curl command, drop the -i flag to output only the JSON data without the header information.

like image 177
Inian Avatar answered Oct 25 '22 15:10

Inian