Skip to content

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.

json_encode(value, array?)
sync
Param Type Description
value any The Lua value to encode
array? boolean If true, all genuinely empty tables become []. Defaults to false.
Value Type Description
json string JSON-encoded string
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 tables become {} by default
json_encode({}) -- "{}"
-- Use JSON_EMPTY_ARRAY to force []
json_encode(JSON_EMPTY_ARRAY) -- "[]"
json_encode({ items = JSON_EMPTY_ARRAY }) -- '{"items":[]}'
-- Or use array=true blanket override
json_encode({ items = {} }, true) -- '{"items":[]}'
get.data = function(self)
return {
status = 200,
body = json_encode({
items = JSON_EMPTY_ARRAY,
meta = {} -- this stays as {}
}),
}
end