Skip to content

JSON (ctx.json) ​

ctx.json converts between Lua values and JSON text. Both functions are synchronous and return a single value.

FunctionReturns
ctx.json.encode(value)a JSON string, with object keys sorted
ctx.json.decode(text)the decoded value (table, string, number, boolean or nil)
lua
local encoded = ctx.json.encode({ method = "POST", retries = 3 })

local decoded = ctx.json.decode(encoded)
return { encoded = encoded, retries = decoded.retries }

Invalid JSON makes decode raise an error. Use pcall when the text comes from outside:

lua
local input = ...
local raw = "{}"
if type(input) == "table" and type(input.payload) == "string" then
  raw = input.payload
end

local parsed, value = pcall(function() return ctx.json.decode(raw) end)
if not parsed then
  ctx.log.warn("payload is not valid JSON", { reason = tostring(value) })
  return { ok = false }
end
return { ok = true, value = value }

Typical uses:

  • building a request body for ctx.device.http, which only sends string bodies;
  • putting GraphQL errors into an error message: error(ctx.json.encode(res.errors)).

There is no XML or base64 encoder in the script API. XML output comes from XML-kind templates.

Connect machines, automate workflows, and build custom apps for print production.