JSON
Encode/decode JSON dari sisi Lua. Backed by serde_json di balik layar. Pasangan ini nempel di global json sebagai function biasa (bukan method call — ga ada arg self).
Methods
json.encode(value)
| Field | Tipe |
|---|---|
| Signature | (value: any) → string |
| Returns | string — teks JSON |
| Common errors | raise kalau value-nya ga bisa direpresentasi serde_json (misal tabel circular, value function) |
| Async | no |
Key numerik berurutan ({1, 2, 3}) ke-serialize jadi array JSON; key campur/string ke-serialize jadi object.
local s = json.encode({ a = 1, b = "hi", c = { 1, 2, 3 } })
-- s = '{"a":1,"b":"hi","c":[1,2,3]}'
json.decode(text)
| Field | Tipe |
|---|---|
| Signature | (text: string) → any |
| Returns | any — value Lua (tabel, string, number, boolean, atau nil) |
| Common errors | raise kalau JSON-nya invalid (json.decode('{not valid}') error, bukan return nil) |
| Async | no |
Array JSON balik sebagai tabel Lua 1-indexed (t[1], bukan t[0] atau t["1"]).
local t = json.decode('{"a":1,"b":"hi","c":[1,2,3]}')
print(t.a, t.b, t.c[1], t.c[2], t.c[3]) -- 1 hi 1 2 3
Round-trip
--!strict
local payload = { name = "asdsa", count = 7, online = true }
local raw = json.encode(payload)
local back = json.decode(raw)
assert(back.name == "asdsa")
assert(back.count == 7)
assert(back.online == true)
Pasangan dengan http
Ga perlu encode manual kalau lagi POST JSON — pass Lua table ke http.post(..., { json = ... }) dan bakal ke-serialize otomatis:
local res = http.post("https://api.example.com/data", {
json = { name = "seraph", count = 42 },
headers = { ["X-Auth"] = "token" },
})
local body = json.decode(res.body)
Lihat HTTP buat shape request/response lengkap.
Catatan kecil
- Boolean round-trip —
true/falseencode dan decode jaditrue/falseJSON. - Key
nildi-drop — Luanilngehapus key; encode skip dia. Pakai sentinel kayak0atau""kalau butuh slot "ada-tapi-kosong". - Ga ada
null— Lua ga punya representasinullJSON;nullyang di-decode jadinil(yang ngehapus key dari table). - Float vs integer — Lua 5.4 bedain
3dari3.0;json.encodejaga bedanya (3→3,3.0→3.0).