2

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

1
  • 1
    You could answer your own question. – RNA Oct 16 '19 at 2:00
0

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.

1
  • Please provide a more detailed answer – Pmpr Apr 1 at 15:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.