Documentation
¶
Overview ¶
Package luajson converts between glua values and JSON, straight from tables to JSON text and back without an intermediate tree, and gives scripts a json module.
A table that is a non-empty sequence, keys 1 to n and no others, becomes a JSON array. Any other table becomes an object, with its keys in sorted order so that the output is deterministic; integer keys become their decimal strings. Strings must be valid UTF-8. Functions, userdata, coroutines, NaN and infinities cannot be encoded, and a float -0 is written as 0. Tables nested more than 64 deep, and tables that contain themselves, are errors.
Decoding gives tables, strings, booleans and numbers: an integer for a number written without a fraction or exponent that fits in 64 bits, a float otherwise. A JSON null is nil, so a null in an array leaves a hole and a null member is absent.
Example ¶
package main
import (
"context"
"fmt"
lua "github.com/folbricht/glua"
"github.com/folbricht/glua/luajson"
)
func main() {
rt := lua.MustNew(luajson.Module("json"))
script, err := rt.Load(context.Background(), "hook.lua", `
function handle(body)
local req = json.decode(body)
return json.encode({user = req.user, items = #req.items, ok = true})
end`)
if err != nil {
panic(err)
}
handle, _ := script.Func1[string, string]("handle")
out, err := handle(context.Background(), `{"user": "ann", "items": [1, 2, 3]}`)
fmt.Println(out, err)
v, _ := luajson.Unmarshal([]byte(`{"port": 8080}`))
b, _ := luajson.Marshal(v)
fmt.Println(string(b))
}
Output: {"items":3,"ok":true,"user":"ann"} <nil> {"port":8080}
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func MarshalWrite ¶
MarshalWrite encodes v as JSON to w.
func Module ¶
Module returns an option that defines a module of the given name, usually "json", with encode(value [, indent]) and decode(text). What decode makes, and the text encode makes, count toward the calling script's budgets.
rt := lua.MustNew(luajson.Module("json"))
-- in Lua: local doc = json.decode(text); local text = json.encode({ok = true})