Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

jq filtering curl- 'Cannot index number with string'

Writer Andrew Mclaughlin

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 "")

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 "")

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 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.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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