Skip to main content

http.jsonencode(value, settings)

Encodes a Squirrel object into JSON data




Name Type Description
value Null, boolean, integer, float, string, array or table The object to encode
settings Table An optional table of encoding settings


String — the JSON data


This method encodes a Squirrel value into JSON (JavaScript Object Notation), as specified in the RFC4627 specification.

The new second parameter, settings, is optional but can be used to provide a table of settings that modify http.jsonenecode()’s output. The following settings are currently available:

Setting Table Key Value Type Description
compact Boolean Set to true to have whitespace removed from between keys and values, and key-value pairs, in the output JSON string. This does not include whitespace that is part of key names and values. See the example, below. Default: false

Many, but not all, types of Squirrel data can be encoded as JSON. Essentially, only those which can be serialized can also be encoded in JSON form. For the specific details, please see Squirrel Data Serialization.

One notable type that isn’t encodable as JSON is blob. Blobs should be first Base64-encoded into strings using http.base64encode().

Tables and arrays can be nested, as long as all the data they contain is serializable. Although Squirrel allows any data type to be used as keys in tables, JSON only accommodates strings. It is possible, then, to construct Squirrel tables that have no valid JSON representation: for instance, one with both 0 (integer) and “0” (string) as keys. This is not the case with JavaScript itself.

The corresponding decoding operation is http.jsondecode().

Example Code

The following snippet shows the use of the compact setting if it’s included in a table passed into the settings parameter.

local t = { "key1  " : "  string  ",
            "key2" : true,
            "key3" : {
                    "key4" : 42,
                    "key5" :     "ZX81"

server.log(http.jsonencode(t, {"compact":true}));

This logs:

2018-09-11 16:45:38.329 +01:00 [Agent]  { "key1  ": "  string  ", "key3": { "key5": "ZX81", "key4": 42 }, "key2": true }

The compact version lacks whitespace between keys and values, and between key-value pairs, and is applied iteratively through the table structure. Whitespace within key and value declarations is not removed. Removing whitespace can result in significantly smaller data sizes (and so takes less time to send) especially if the table being transmitted is large and complex.