Reading JSON from URL in R

Posted on In Programming, Tutorial

R is good at analyzing data. Many data are provided as JSON from RESTful APIs with an URL. R natively support many data format. For JSON, we can use some libraries. For reading JSON from URL, we can use the “jsonlite” package. In this example, we use an example of fetching BTC prices of last year to introduce how to read JSON data from RESTful API directly in R.

We need to first install “jsonlite” library package in R if it is not installed yet (only need to this once).

install.packages("jsonlite")

With the “jsonlite” library package installed in our R environment, in our R program, we can import the “jsonlite” library.

library("jsonlite")

Then we can call the jsonlite::fromJSON() library function to fetch the JSON data from the RESTful API URL, and convert the JSON object to a matrix.

btc <- jsonlite::fromJSON("https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1d&limit=365")

We can check the btc variable content.

We can also plot the matrix data out.

Easy and quick. Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *