lightweight and efficient library for encoding Lua values into JSON strings and decoding JSON strings back into Lua data structures. It supports standard Lua types such as tables, numbers, strings, booleans, and nil
- Encoding Lua → JSON
Converts Lua values to JSON format, handling tables (as arrays or objects), strings with proper escaping, numbers, booleans, and a special json.null value representing JSON null. - Decoding JSON → Lua
Parses JSON strings into corresponding Lua types, supporting objects, arrays, strings, numbers, booleans (true/false), and JSON null (converted to Lua nil). - Configurable Encoding Options
Supports pretty-printing (indentation and new lines), sorting object keys lexicographically, controlling maximum recursion depth, and allowing or disallowing sparse arrays. - Error Handling & Safety
Provides safe encode and decode functions (encodeSafe and decodeSafe) that return nil plus an error message instead of throwing errors, making it easier to handle invalid data gracefully. - Cycle Detection
Detects and prevents infinite loops when encoding tables with circular references by raising an error. - Custom Serialization Support
Allows custom JSON serialization via the __tojson metamethod on Lua tables, letting you define how your objects are converted to JSON. - UTF-8 and Unicode Handling
Correctly parses and encodes Unicode escape sequences, including surrogate pairs.
local json = require("json") -- assuming your module file is named json.lua
-- Example Lua table with various types including json.null
local data = {
name = "Alice",
age = 30,
isActive = true,
scores = {100, 98, 95},
misc = json.null, -- JSON null value
}
-- Encode Lua table to JSON string
local json_str = json.encode(data, { pretty = true, sort_keys = true })
print("Encoded JSON:\n" .. json_str)
-- Decode JSON string back to Lua table
local decoded_table = json.decode(json_str)
print("Decoded Lua table:")
for k,v in pairs(decoded_table) do
print(k, v)
end
-- Safe encoding example (catches errors)
local ok, result_or_err = json.encodeSafe(data)
if ok then
print("Safe encode success:", result_or_err)
else
print("Safe encode error:", result_or_err)
end
-- Safe decoding example (catches errors)
local bad_json = '{"name": "Bob", "age": "twenty"}' -- valid JSON but 'age' is string here
local decoded, err = json.decodeSafe(bad_json)
if decoded then
print("Safe decode success:", decoded.name, decoded.age)
else
print("Safe decode error:", err)
end