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
| Name | Type | Description |
|---|---|---|
| Encode | Shared | Encodes a value as a JSON string. |
| Decode | Shared | Decodes a JSON string into a script value. |
Shared Functions
Encode
Encodes a value as a JSON string.
string json = JSON.Encode(any value)
How tables are encoded:
- Lua has a single table type, so the keys decide the shape. A table whose keys are exactly
1..nwithout 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 (
1becomes"1"). A table or a function used as a key is skipped.
Values may not be nested deeper than 32 levels. If they are, the function raises a script error.
Example:
- Lua
- Squirrel
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]
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)
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.
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.
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:
- Lua
- Squirrel
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)
local result = HTTP.Request("https://httpbin.org/get", "get", "", "application/json", {});
local data = JSON.Decode(result[1]);
if (data == null) {
Console.Log("Invalid JSON response.");
return;
}
Console.Log("url: " + data.url);