0

I am using curl to create a session to log into the switch. Below the script that i use

curl --noproxy 10.23.193.1 -X POST http://10.23.193.1:80/rest/v3/login-sessions -d '{"userName":"admin", "password":"password"}'

After this is executed I get the following output

{"uri":"/login-sessions","cookie":"sessionId=DfZNCFbfoc3LDuMgjLXRiS8ZmEo4MWENCOJM0Iu14R1uMT9kKqbe1Rx6AedmoeT"}

My requirement here is to first only print this part of the string "sessionId=DfZNCFbfoc3LDuMgjLXRiS8ZmEo4MWENCOJM0Iu14R1uMT9kKqbe1Rx6AedmoeT"

Secondly I would want to know how to store the above string in a variable so that I could call the same variable for subsequent operations

I ran the following, but I am not getting any output.

curl --noproxy 10.23.193.1 -X POST http://10.23.193.1:80/rest/v3/login-sessions -d '{"userName":"admin", "password":"password"}' | grep -`E ""cookie":"
0

1 Answer 1

2

Avoid using simple tools like grep or sed to parse JSON as they won't handle things like quotes or multi-line data correctly. It's best to use a JSON-aware program such as jq.

With jq it's simple and robust:

curl ... | jq '.cookie'

To store the cookie in a variable use the -r flag to have JQ print out the raw, unquoted string.

cookie=$(curl ... | jq -r '.cookie')

Further reading:

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. You are awesome. Will figure out a way to install jq and go from there. Thank you loads

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.