Skip to main content

JSON

Converts script values to JSON text and back. Useful for HTTP payloads, WebUI communication and for storing structured data in a Database column.

Quick Reference

NameTypeDescription
EncodeSharedEncodes a value as a JSON string.
DecodeSharedDecodes a JSON string into a script value.

Shared Functions

Encode

Encodes a value as a JSON string.

string json = JSON.Encode(any value)

info

How tables are encoded:

  • Lua has a single table type, so the keys decide the shape. A table whose keys are exactly 1..n without gaps becomes a JSON array, everything else becomes a JSON object. An empty table becomes an object ({}).
  • Squirrel has a real array type: arrays become JSON arrays, tables become JSON objects.
  • Number keys in an object are written as their text form (1 becomes "1"). A table or a function used as a key is skipped.
warning

Values may not be nested deeper than 32 levels. If they are, the function raises a script error.

Example:

Console.Log(JSON.Encode({ name = "Niko", level = 3, online = true }))
-- {"name":"Niko","level":3,"online":true}

Console.Log(JSON.Encode({ 1, 2, 3 }))
-- [1,2,3]

Decode

Decodes a JSON string into a script value.

any value = JSON.Decode(string json)

info

A JSON object always becomes a table. A JSON array becomes a Squirrel array, and in Lua a table keyed 1..n, the shape ipairs and the length operator expect.

warning

Invalid input is not a script error: the function returns nil/null and writes the parse position and reason to the server/client log. Always check the return value before using it, because a remote host can answer with an error page at any time.

caution

Numbers come back as a 32-bit int or a single-precision float and nothing wider. A JSON number too large for an int arrives as a float and loses its last digits, so IDs from an external API should be sent and read as strings.

Example:

local status, body = HTTP.Request("https://httpbin.org/get", "get", "", "application/json", {})

local data = JSON.Decode(body)
if data == nil then
Console.Log("Invalid JSON response.")
return
end

Console.Log("url: " .. data.url)