json_encode
json_encode(value, array?) converts a Lua table or value into a JSON string. Uses SpyWeb’s built-in high-performance JSON engine, handling nested tables, arrays, booleans, and nulls automatically.
Empty Lua tables {} serialize as {} by default. Use JSON_EMPTY_ARRAY to force [], or pass array=true to treat all empty tables as arrays.
Signature
Section titled “Signature”json_encode(value, array?)
syncParameters
Section titled “Parameters”| Param | Type | Description |
|---|---|---|
value |
any | The Lua value to encode |
array? |
boolean | If true, all genuinely empty tables become []. Defaults to false. |
Returns
Section titled “Returns”| Value | Type | Description |
|---|---|---|
| json | string | JSON-encoded string |
Examples
Section titled “Examples”Basic usage
Section titled “Basic usage”local payload = { url = "https://example.com", options = { waitUntil = "networkidle2" }}local body = json_encode(payload)local resp = http_post("https://api.rendering-service.com/render", body, {["Content-Type"]="application/json"})Empty arrays
Section titled “Empty arrays”-- Empty tables become {} by defaultjson_encode({}) -- "{}"
-- Use JSON_EMPTY_ARRAY to force []json_encode(JSON_EMPTY_ARRAY) -- "[]"json_encode({ items = JSON_EMPTY_ARRAY }) -- '{"items":[]}'
-- Or use array=true blanket overridejson_encode({ items = {} }, true) -- '{"items":[]}'Server response
Section titled “Server response”get.data = function(self) return { status = 200, body = json_encode({ items = JSON_EMPTY_ARRAY, meta = {} -- this stays as {} }), }endSee Also
Section titled “See Also”- JSON_EMPTY_ARRAY - Sentinel value for empty JSON arrays
- json_decode - Parse JSON string to Lua table