Score:0

Capture a string from JSON response

jp flag
sai

I have below Json response for POST method in bash and would like to capture value after sessionId":" and assign it to variable session_ID.

{"changeId":"79911476-53a4-46e1-8ffd-422436b51ad1","changeType":"created","record":{"key":"159.65.198.219"}},{"changeId":"bd52dcbd-a5ab-4557-b2b8-88793c2d2964","changeType":"created","record":{"key":"161.35.111.167"}},{"changeId":"f4f5c94e-6c06-473c-b810-b7bbd69c71ad","changeType":"created","record":{"key":"161.35.123.111"}}],"sessionId":"b7305d77-20f1-4d57-9eb1-9b9fb4f9552d"}

#API call

request_post="$(curl --insecure --request POST "endpoint_URL")"

echo $request_post

I need help to complete below step

#Cut out sessionId from response

session_ID=

 

FedKad avatar
cn flag
You should use the `jq` command. Google "How use jq command in Linux"
hr flag
If you want help with `jq`, please make sure that your example is a complete parsable JSON fragment
Score:0
cn flag

While parsing json structures should be done by a json parser, trivial cases like this can be done with a trivial tool and you may pipe the answer though sed, for example:

sed 's/.*"sessionId":"\([^"]*\).*/\1/'
      \______________/  \___/  \/
             A            B    C

A matches everything upto and including "sessionId":", B matches all following non-", which is the actual sessionId, and C matches the rest of the line. B is included in \(\), so it can be referred to in the replacement as \1. So the whole line is replaced by the sessionId only.

Of course, if the output can be split over several lines or uses other variations allowed by json format, the script will get more complicated.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.