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 ({}).
  • JavaScript and Squirrel have a real array type: arrays become JSON arrays, objects and 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.
JavaScript

JSON.Encode and JSON.Decode live on the same JSON object as the language's own JSON.stringify and JSON.parse, and all four work. JSON.Encode and JSON.Decode behave the same in every language (table shapes, nesting limit and numbers as described on this page), JSON.stringify and JSON.parse are the ones built into JavaScript.

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 (an object in JavaScript). A JSON array becomes a JavaScript or 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 64-bit integers or double-precision floats. A whole JSON number beyond the 64-bit range arrives as a float and loses its last digits, and in JavaScript the limits of event arguments apply. IDs from an external API are safest 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)