How to parse a system(curl) response into workspace variables

8 views (last 30 days)
Hello- Can anyone provide some insight into how to properly parse the system(curl) response into matlab.
It is currently returned into a string field, but I need to get the individual name/value pairs as variables.
No doubt there is a better way to make this request using webread, but I have been unsuccessful in formatting the headers properly, so have been using curl.
The objective is to pull these two pairs and save them as seperate variables in matlab
"access_token" : "n0f9jeyyc"
"expires_in" : 1800
The system(curl) request (with token abbreviated)
>>>>>>>
command = 'curl -X POST --header "Content-Type: application/x-www-form-urlencoded" -d "grant_type=refresh_token&refresh_token=uc80SIH3400B75E&access_type=&code=&client_id=CPUNQFIRUX1FHKWW8XJO7DMZWRCRQGMU%40AMER.OAUTHAP&redirect_uri=http%3A%2F%2Flocalhost" "https://api.tdameritrade.com/v1/oauth2/token"';
[response, curl_response] = system(command);
>>>>>>>
The response which is placed in one large string;
%%%%%
curl_response =
' % Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
100 2636 100 1489 100 1147 5304 4086 --:--:-- --:--:-- --:--:-- 9448
{
"access_token" : "n0f9jeyyc",
"scope" : "PlaceTrades AccountAccess MoveMoney",
"expires_in" : 1800,
"token_type" : "Bearer"
}'
%%%%%

Answers (1)

Poorna
Poorna on 21 Sep 2023
Edited: Poorna on 21 Sep 2023
Hello Dwayne,
I understand that you are looking to parse the response returned by the system function after running the cURL command and extract the values of "access_token" and "expires_in".
You can follow the below steps to achieve this:
  • Use the “regexp function to extract the JSON portion from the curl_response string. This can be done by searching for the pattern enclosed within curly braces.
jsonStr = regexp(curl_response, '{.*}', 'match', 'once');
  • Next, utilize the jsondecode function to parse the extracted JSON string and convert it into a MATLAB struct.
jsonData = jsondecode(jsonStr);
  • Finally, access the individual name/value pairs ("access_token" and "expires_in") from the parsed JSON data using the dot operator.
% Access the individual name/value pairs as variables
access_token = jsonData.access_token;
expires_in = jsonData.expires_in;
Please refer to the following documentation for more information on the functions used:
Hope this Helps!

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!