Jq filtering curl- ‘Cannot index number with string’

curljson

I am trying to filter a curl request with jq to get specific fields and put them in variables. Initially, I was using a basic curl request such as this:

myResponse=$(curl -u myUsername:myPassword -XGET "https://myWebsite.com/_count?pretty&q=TEST")

I am providing my username and password, and getting a count for how many times the term 'TEST' is present, which is returned in pretty json. This response is put into a variable called myResponse.

I used jq to filter this to get a specific count value from the json:

count=`echo $myResponse | jq -r '.count'`

This worked, and provided me with a number.

So now I wanted to experiment a bit. As well as getting the response from the curl request I also wanted to retrieve the response code (200, 404 etc). So I adapted my curl request to the following:

myResponse=$(curl --write-out %{http_code} --silent -u myUsername:myPassword -XGET "https://myWebsite.com/_count?pretty&q=DEBUG")

This successfully returned both the JSON response and then after this it returned the http response code as a number.

However, once this is passed into jq, I get the following error:

jq: error: Cannot index number with string

How do I resolve this error? When it was just json jq handled it fine, but as soon as this responsecode was added onto the end it can't parse it.

Thanks

Best Answer

There was both JSON and HTTP in the variable I was piping into jq. You first must split the variable into JSON and HTTP using tail and head. Once I piped pure JSON into jq, it worked.

Related Question