Skip to main content

Encoding Containers To JSON On The Device

Iterate Through Complex Data Structures

While agents have access to the imp API method http.jsonencode() for converting tables to JSON strings, devices do no. Fortunately, it’s relatively easy to implement on in Squirrel (albeit one that’s not as quick as the native agent version), as the code below demonstrates.

This has the added advantage of demonstrating how you can iterate over a complex Squirrel data structure: a container object such as a table or an array which contains nested containers, sometimes many levels deep.

The recipe code mirrors http.jsonencode() in that it takes a container as its first. mandatory argument and, optionally, a table of options as a second argument. Only one key, compact, is supported in the options table: if its value is set to true, whitespace is eliminated from the output (excluding whitespace within keys or values).

For example, if the following device code (assuming the recipe is included first) is run:

// Set up a sample table
local t = {};
t.astring <- "Hello World";
t.abool <- true;
t.anint <- 42;
t.anarray <- ["one", 2, "three", 4];
t.atable <- {};
t.atable = clone t;
t.atable.atable = {"text" : "string", "boolean" : false};
t.anarray.append({"text" : "string", "boolean" : false});
server.log("\n**** Expanded ****\n" + jsonencode(t) + "\n**** Compact  ****\n" + jsonencode(t, {"compact":true}));

the following output will be generated:

2018-12-04 15:07:04.086 +00:00 "Explorer": [Device]    
**** Expanded ****
{ 'anarray' : [ 'one', 2, 'three', 4, { 'text' : 'string',
                                        'boolean' : false } ],
  'anint' : 42,
  'abool' : true,
  'astring' : 'Hello World',
  'atable' : { 'anarray' : [ 'one', 2, 'three', 4, { 'text' : 'string',
                                                     'boolean' : false } ],
               'anint' : 42,
               'abool' : true,
               'astring' : 'Hello World',
               'atable' : { 'text' : 'string',
                            'boolean' : false } } }
**** Compact  ****
{'anarray':['one',2,'three',4,{'text':'string','boolean':false}],'anint':42,'abool':true,'astring':'Hello World','atable':{'anarray':['one',2,'three',4,{'text':'string','boolean':false}],'anint':42,'abool':true,'astring':'Hello World','atable':{'text':'string','boolean':false}}}

Sample Code