Forum Moderators: bakedjake

Message Too Old, No Replies

Bash scripting, using curl / json results

         

csdude55

10:02 pm on Nov 24, 2023 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



It's been a minute since I had to do any bash scripting :-O

I'm using cURL to get a JSON response from another site, and then I need to use one of the JSON values in the next part of my script. My cURL looks like this:

# can I use spaces here?
var = 9876;

# can I use $var inside of the ` ` here?
response = `curl https://example.com?id=$var \
-H 'Content-Type: application/json' \
foo`

The result looks like:

{"result":{"id":"1234","name":"bar.com","status":"pending",...}

How do I get "id" in the next section of the script?

csdude55

6:28 am on Nov 25, 2023 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Answering my own question, kinda, but I've learned that bash doesn't really understand JSON out of the box, so you need something like jq to parse it properly.

In theory, like this:

response=`curl https://example.com?id=$var \
-H 'Content-Type: application/json' \
foo` | jq '.result[0].id'

And then $response would be the value of id. I'm not sure how to do it if you needed more than one value, though.

But in my case, I can't get jq to install! It shows a successful install, but on running it I get:

jq: error while loading shared libraries: libonig.so.5: cannot open shared object file: No such file or directory


I think I'm going to have to abandon this project, it was supposed to be a fun refresher for a few hours, not a 2-day project! LOL

To answer the other two questions:

1. No, I can't use spaces; I immediately get an error where it thinks that the variable name is a command

2. Yes, I can use variables inside of ` `

csdude55

7:14 pm on Nov 25, 2023 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



For future readers getting the same error with jq, I found this as a solution but I haven't tried it yet:

yum install oniguruma -y
yum install libsodium -y