View Raw SPL
/*****************************************************************************
* *
* WEBREADJSON.SPL Copyright (C) 2020 DSP Development Corporation *
* All Rights Reserved *
* *
* Author: Randy Race *
* *
* Synopsis: Returns a JSON object from a URL *
* *
* Revisions: 20 Aug 2020 RRR Creation *
* *
*****************************************************************************/
#include
#if @HELP_WEBREADJSON
WEBREADJSON
Purpose: Returns a JSON object from a URL.
Syntax: WEBREADJSON("url", "header")
"url" - A string, the URL string.
"header" - Optional. A string, the HTML header. Defaults to
"Content-Type: application/json"
Returns: An object, the JSON object for the URL.
Example:
webreadjson("https://ipinfo.io/json")
Displays an object that contains information on the current
IP address.
Example:
webreadjson("http://dummy.restapiexample.com/api/v1/employees")
Displays an object where the DATA property contains 24
mocked employee records.
Example:
dspobj = webreadjson("http://dummy.restapiexample.com/api/v1/employees")
Same as above except the returned JSON object is assigned to the
variable DSPOBJ.
Remarks:
WEBREADJSON returns a JSON object for the input URL. The initial
returned JSON string is converted to an object.
If no output is provided, the object is displayed in a pop-up
dialog box.
See Also:
Geturl
Objjson
Viewjson
Webreadhtml
Webreadimage
#endif
/* return JSON object for a URL */
webreadjson(url = {}, header = "Content-Type: application/json")
{
local jstr, jobj, status, err, errstr;
if (not(isstring(url)) || strlen(url) == 0)
{
error(sprintf(_rdterr_iur, __FUNC__));
}
/* check URL syntax */
if (not(isvalidurl(url)))
{
/* check if regular file */
if (fileexists(url))
{
/* read json file */
jobj = readjson(url);
return(jobj);
}
else
{
error(sprintf(_rdterr_inu, __FUNC__, url));
}
}
else
{
/* valid url */
header = webformatheader(header);
/* get JSON string */
(jstr, status, err) = webreadstr(url, header);
if (status == 1)
{
/* convert to object */
jobj = objjson(jstr);
return(jobj);
}
else
{
/* error */
if (isstring(err) && strlen(err) > 0)
{
errstr = err;
}
else if (isstring(jstr) && strlen(jstr) > 0)
{
errstr = jstr;
}
else
{
errstr = sprintf("%d", status);
}
error(sprintf("%s - %s", __FUNC__, errstr));
}
}
}