Interact, learn and grow

Join Now
Reply
This is an open group. Sign in and click the "Join Group" button to become a group member and start posting.
Highlighted
SAS Employee
Posts: 2
Juletip #10 – Bring some awesomeness to your day with Chuck Norris and libname JSON

The_Legend2.jpg(drawing courtesy of Sanna Ovaskainen)

For those who don’t know, Chuck Norris is a legendary 80s action hero and also one of my childhood icons. There are countless proverbs written about his supernatural abilities. I found a cool site https://api.chucknorris.io/ that has a JSON API which provides a random Chuck Norris factoid with every query.

 

This tiny SAS example describes how easy it it to use SAS for querying APIs that provide JSON output. We use PROC HTTP with GET for the query and the recent JSON libname engine (part of SAS 9.4 since M4) for reading the response file into SAS. Example (from the website) response looks like this:

 

 {
                "icon_url" : "https://assets.chucknorris.host/img/avatar/chuck-norris.png",
                "id" : "OlXgZ60VRGyxb7d7FcM1EA",
                "url" : "http://api.chucknorris.io/jokes/OlXgZ60VRGyxb7d7FcM1EA"
                "value" : "Chuck Norris can burn water."

 }

 

We assign a JSON libname to this response and get two tables: ALLDATA and ROOT. ALLDATA contains the data from the response. Chuck factoid is in column “value” and can be found on the row where P1=’value’.

 

From there it’s business as usual with PROC PRINT and outputting just the content we want – your awesome Chuck Norris factoid of the day.

 

/* Assign filename 'resp' for the response*/
 filename resp temp;

/* Query api.chucknorris.io service */
/* at https://api.chucknorris.io/jokes/random */
proc http
 url="https://api.chucknorris.io/jokes/random"
 method= "GET"
 out=resp;
run;

/* Assign a JSON library to the HTTP response */
libname chuck JSON fileref=resp;

/* Print row 'value' from column P1 of ALLDATA dataset */
proc print data=chuck.ALLDATA noobs label;
 title "Retrieved from api.chucknorris.io JSON API";
 var value;
 label value="Your awesome Chuck Norris factoid of the day";
 where P1="value";
run;