QueryToJSON Plugin

The QueryToJSON Plugin file contains a function for converting database query result arrays to the JSON format.

Loading this Plugin

This plugin is loaded using the following code:

rigLoadPlugin "querytojson"

The function:

rigQueryToJSON(pResult, pFieldnames)

The first parameter is a database query result array. The optional second parameter is an array containing the field names of the database table. Example:

put mymodelFetchAllData("recipe") into tQuery
put tQuery["resultarray"] into tResult
put tQuery["fieldnames"] into tFieldNames

put rigQueryToJSON(tResult, tFieldNames) into gData["jsonData"]

Conversion example:

Input: database table

1Banana BreadHow to make banana bread.
2PancakesHow to make pancakes.

Output: JSON

"Name":"Banana Bread",
"Directions":"How to make banana bread."
"Directions":"How to make pancakes."

To reference the JSON object use the term "queryToJSON". To reference individual items of the JSON records use the table field names. If the "fieldnames" parameter is empty, item names are "field1", "field2", "field3" ... etc. Example:

rigJQeventOpen "'#go'", "'click'"
put "getjsontest/getjsondata" into tAjax["url"]
put "'json'" into tAjax["dataType"]

put rigJQvarR("jsObj, data;") & return into tSuccess
put rigJQsetR("'#resultData'", "append", "'<p>' + element.myTabeleFieldName + '</p>'") into tCallback
put rigJQeachOpenR("jsObj.queryToJSON", , tCallback) && rigJQeachCloseR() after tSuccess

put tSuccess into tAjax["success"]

rigJQajax tAjax


put the result into gData["JQscript"]

In the example above we perform an Ajax request. We store the retrieved data in a variable called "jsObj" and reference the JSON object with "jsObj.queryToJSON". We iterate over the JSON object using "element.myTabeleFieldName" for an item "myTabeleFieldName" in each JSON record "element" where "myTabeleFieldName" is the name of a database tabel field and "element" is an argument of the JQuery .each function (rigJQeachOpenR).