go-lua-json
A GopherLua module for JSON encoding and decoding in Lua scripts.
Installation
go get github.com/kerimovok/go-lua-json
Usage
In Go
import (
lua "github.com/yuin/gopher-lua"
json "github.com/kerimovok/go-lua-json"
)
L := lua.NewState()
defer L.Close()
// Preload the json module
L.PreloadModule("json", json.Loader)
// Now Lua scripts can use require("json")
L.DoString(`
local json = require("json")
local data = {name = "John", age = 30}
local encoded = json.encode(data)
local decoded = json.decode(encoded)
print(decoded.name) -- prints "John"
`)
In Lua
local json = require("json")
-- Encode a table to JSON string
local data = {name = "John", age = 30, tags = {"developer", "golang"}}
local jsonStr = json.encode(data)
-- jsonStr = '{"name":"John","age":30,"tags":["developer","golang"]}'
-- Decode a JSON string to a table
local decoded, err = json.decode(jsonStr)
if err then
error("Failed to decode: " .. err)
end
print(decoded.name) -- "John"
print(decoded.tags[1]) -- "developer"
Functions
json.encode(value)
Converts a Lua value (table, string, number, boolean, nil) to a JSON string.
- Parameters:
value: The Lua value to encode
- Returns:
string: JSON string representation
string (error): Error message if encoding fails
json.decode(str)
Parses a JSON string and returns a Lua table.
- Parameters:
str: JSON string to parse
- Returns:
table: Decoded Lua table (or nil on error)
string (error): Error message if decoding fails
Notes
- Arrays in JSON are converted to Lua tables with integer keys (1-indexed)
- Objects in JSON are converted to Lua tables with string keys
null in JSON is converted to nil in Lua
- Numbers are preserved as Lua numbers