R/sonarJSON.R

#
#  Copyright 2014 jSonar Inc
#  All Rights Reserved.
#
#  Licensed under the GNU AFFERO GENERAL PUBLIC LICENSE version 3
#  See http://www.r-project.org/Licenses/AGPL-3
#

#' Get a JSON document for a saved query
#'
#' Execute a query which has been saved and published in JSON Studio Finder,
#' and get the response in an R object that is structured like a JSON
#' document. This object is generated by the jsonlite package.
#'
#' The parameters for this function are explained in greater detail in the
#' JSON Studio help page \emph{Using the Gateway}.
#'
#' @param connection a SonarConnection object created with
#'   \code{\link{new.SonarConnection}}
#' @param queryName the name of the saved query to execute
#' @param queryCol a collection in the database to use with the query
#' @param type the type of query to execute ('agg' or 'find')
#' @param bind a list of bind variables and their values
#' @param limit the maximum number of results to return
#' @param publishedBy the name of the user who we expect published the API
#'
#' @examples
#' connection <- new.SonarConnection('https://example.com', 'localhost', 'test')
#'
#' delays <- sonarJSON(connection, 'delayed_flights', 'ExampleFlights', type='find', limit=5)
#' summary(delays$Origin$city)
#' 
#'
#' @export
#' @keywords database
#'
#' @family connection
#' @family json
#' @seealso \url{http://jsonstudio.com/wp-content/uploads/2014/04/manual141/_build/html/index.html}
sonarJSON <- function(connection, queryName, queryCol, type, bind=list(), limit=NULL, publishedBy=NULL)
{
    gatewayURL <- sonarGatewayURL(connection, queryName, queryCol, 'json', type, bind, limit, publishedBy);

    if(gatewayURL %in% names(exampleData)) {
        jsonData <- exampleData[gatewayURL]
    } else {
        jsonData <- RCurl::getURL(gatewayURL, ssl.verifypeer=FALSE, ssl.verifyhost=FALSE);
    }

    if(substring(jsonData, 1, 9) == '"errors":')
    {
        # detect errors from the server (Gateway doesn't return an error response code)
        stop(jsonData);
    } else {
        json <- fromJSON(jsonData)
        return(json$output);
    }
}

Try the jSonarR package in your browser

Any scripts or data that you put into this service are public.

jSonarR documentation built on May 2, 2019, 4:01 p.m.