### Lua to JSON Type Conversion and Encoding Example (Go) Source: https://context7.com/alicebob/gopher-json/llms.txt Demonstrates bidirectional type conversions between Lua and JSON using the gopher-json library. It showcases encoding various Lua types (nil, boolean, number, string, table) into their JSON representations and prints the results. The example requires the gopher-lua and gopher-json libraries. ```go package main import ( "fmt" "github.com/yuin/gopher-lua" luajson "layeh.com/gopher-json" ) func main() { L := lua.NewState() defer L.Close() luajson.Preload(L) L.DoString(` local json = require("json") -- Demonstrate all supported type conversions local examples = { {input = nil, expected = "null"}, {input = true, expected = "true"}, {input = false, expected = "false"}, {input = 42, expected = "42"}, {input = 3.14, expected = "3.14"}, {input = "text", expected = '"text"'}, {input = {}, expected = "[]"}, {input = {1,2,3}, expected = "[1,2,3]"}, {input = {a=1}, expected = '{"a":1}'}, } for _, ex in ipairs(examples) do local result = json.encode(ex.input) print(string.format("% -12s -> %s", tostring(ex.input), result)) end `) } ``` -------------------------------- ### Encode Lua Values to JSON with gopher-lua Source: https://context7.com/alicebob/gopher-json/llms.txt This Go snippet demonstrates the `json.encode()` function from the gopher-json library, showing its ability to convert various Lua types (primitives, arrays, objects, nested structures) into JSON strings. It also includes examples of error handling for invalid inputs like sparse arrays, mixed key types, and circular references. ```go package main import ( "fmt" "github.com/yuin/gopher-lua" luajson "layeh.com/gopher-json" ) func main() { L := lua.NewState() defer L.Close() luajson.Preload(L) err := L.DoString(` local json = require("json") -- Encode primitive types print(json.encode(true)) -- Output: true print(json.encode(42)) -- Output: 42 print(json.encode("hello")) -- Output: "hello" print(json.encode(nil)) -- Output: null -- Encode arrays (sequential numeric keys starting at 1) print(json.encode({1, 2, 3})) -- Output: [1,2,3] print(json.encode({"a", "b"})) -- Output: ["a","b"] print(json.encode({})) -- Output: [] -- Encode objects (string keys only) local user = {name = "Bob", active = true} print(json.encode(user)) -- Output: {"active":true,"name":"Bob"} -- Nested structures local nested = { person = {name = "Tim", age = 25}, scores = {100, 95, 88} } print(json.encode(nested)) -- Output: {"person":{"age":25,"name":"Tim"},"scores":[100,95,88]} -- Error handling: sparse arrays not allowed local result, err = json.encode({1, 2, [10] = 3}) if err then print("Error:", err) end -- Output: Error: cannot encode sparse array -- Error handling: mixed key types not allowed local result, err = json.encode({1, 2, name = "test"}) if err then print("Error:", err) end -- Output: Error: cannot encode mixed or invalid key types -- Error handling: circular references not allowed local a = {value = 1} local b = {ref = a} a.circular = b local result, err = json.encode(a) if err then print("Error:", err) end -- Output: Error: cannot encode recursively nested tables to JSON `) if err != nil { fmt.Println("Error:", err) } } ``` -------------------------------- ### Register JSON Module with gopher-lua Source: https://context7.com/alicebob/gopher-json/llms.txt This snippet demonstrates how to preload the JSON module into a gopher-lua state, making it available for Lua scripts to use via `require('json')`. It shows basic encoding and decoding of Lua tables to and from JSON strings. ```go package main import ( "fmt" "github.com/yuin/gopher-lua" luajson "layeh.com/gopher-json" ) func main() { L := lua.NewState() defer L.Close() // Preload the JSON module luajson.Preload(L) // Now Lua scripts can use require("json") err := L.DoString(` local json = require("json") -- Encode a Lua table to JSON local data = {name = "Alice", age = 30} local jsonStr = json.encode(data) print("Encoded:", jsonStr) -- Output: Encoded: {"age":30,"name":"Alice"} -- Decode JSON back to Lua table local decoded = json.decode(jsonStr) print("Name:", decoded.name, "Age:", decoded.age) -- Output: Name: Alice Age: 30 `) if err != nil { fmt.Println("Error:", err) } } ``` -------------------------------- ### Register JSON Module with Custom Name in gopher-lua Source: https://context7.com/alicebob/gopher-json/llms.txt This code illustrates how to register the JSON module under a custom name using `L.PreloadModule` in gopher-lua. This allows Lua scripts to `require` the module using the specified custom name, as shown with 'JSON'. ```go package main import ( "fmt" "github.com/yuin/gopher-lua" luajson "layeh.com/gopher-json" ) func main() { L := lua.NewState() defer L.Close() // Register JSON module under custom name "JSON" L.PreloadModule("JSON", luajson.Loader) err := L.DoString(` local JSON = require("JSON") local result = JSON.encode({status = "ok", code = 200}) print(result) -- Output: {"code":200,"status":"ok"} `) if err != nil { fmt.Println("Error:", err) } } ``` -------------------------------- ### Encode and Decode JSON using Go API Source: https://context7.com/alicebob/gopher-json/llms.txt The Gopher-JSON library provides direct Go functions for encoding Lua values into JSON byte slices and decoding JSON byte slices into Lua values. It also includes `DecodeValue` for converting Go's `interface{}` types to Lua values. ```go package main import ( "fmt" "github.com/yuin/gopher-lua" luajson "layeh.com/gopher-json" ) func main() { L := lua.NewState() defer L.Close() -- Encode Lua values directly from Go table := L.NewTable() table.RawSetString("message", lua.LString("Hello from Go")) table.RawSetString("count", lua.LNumber(42)) jsonBytes, err := luajson.Encode(table) if err != nil { fmt.Println("Encode error:", err) return } fmt.Println("Encoded:", string(jsonBytes)) // Output: Encoded: {"count":42,"message":"Hello from Go"} -- Decode JSON directly to Lua values from Go jsonStr := `{"status": "success", "data": [1, 2, 3]}` luaValue, err := luajson.Decode(L, []byte(jsonStr)) if err != nil { fmt.Println("Decode error:", err) return } // Access decoded values if tbl, ok := luaValue.(*lua.LTable); ok { status := tbl.RawGetString("status") fmt.Println("Status:", status.String()) // Output: Status: success data := tbl.RawGetString("data").(*lua.LTable) fmt.Println("First item:", data.RawGetInt(1).String()) // Output: First item: 1 } -- DecodeValue for converting Go interface{} to Lua values goData := map[string]interface{}{ "name": "Test", "values": []interface{}{10, 20, 30}, } luaVal := luajson.DecodeValue(L, goData) if tbl, ok := luaVal.(*lua.LTable); ok { fmt.Println("Name:", tbl.RawGetString("name").String()) // Output: Name: Test } } ``` -------------------------------- ### Decode JSON to Lua Values using Lua API Source: https://context7.com/alicebob/gopher-json/llms.txt The `json.decode()` Lua function parses a JSON string into Lua values. It handles primitive types, arrays, objects, and nested structures. Invalid JSON input results in nil and an error message. This function is part of the 'json' module preloaded by `luajson.Preload(L)`. ```go package main import ( "fmt" "github.com/yuin/gopher-lua" luajson "layeh.com/gopher-json" ) func main() { L := lua.NewState() defer L.Close() luajson.Preload(L) err := L.DoString(` local json = require("json") -- Decode primitive types print(json.decode("true")) -- Output: true print(json.decode("123.45")) -- Output: 123.45 print(json.decode('"hello"')) -- Output: hello print(json.decode("null")) -- Output: nil -- Decode arrays local arr = json.decode("[1, 2, 3]") print(arr[1], arr[2], arr[3]) -- Output: 1 2 3 -- Decode objects local obj = json.decode('{"name": "Alice", "age": 30}') print(obj.name, obj.age) -- Output: Alice 30 -- Decode nested structures local data = json.decode([[ { "users": [ {"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"} ], "total": 2 } ]]) print(data.total) -- Output: 2 print(data.users[1].name) -- Output: Alice print(data.users[2].name) -- Output: Bob -- Error handling: invalid JSON local result, err = json.decode("invalid json") if err then print("Parse error:", err) end -- Output: Parse error: invalid character 'i' looking for beginning of value -- Round-trip encoding and decoding local original = {key = "value", nums = {1, 2, 3}} local roundtrip = json.decode(json.encode(original)) print(roundtrip.key) -- Output: value print(roundtrip.nums[2]) -- Output: 2 `) if err != nil { fmt.Println("Error:", err) } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.