Lewati ke konten utama

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)

FieldTipe
Signature(value: any) → string
Returnsstring — teks JSON
Common errorsraise kalau value-nya ga bisa direpresentasi serde_json (misal tabel circular, value function)
Asyncno

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)

FieldTipe
Signature(text: string) → any
Returnsany — value Lua (tabel, string, number, boolean, atau nil)
Common errorsraise kalau JSON-nya invalid (json.decode('{not valid}') error, bukan return nil)
Asyncno

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-triptrue/false encode dan decode jadi true/false JSON.
  • Key nil di-drop — Lua nil ngehapus key; encode skip dia. Pakai sentinel kayak 0 atau "" kalau butuh slot "ada-tapi-kosong".
  • Ga ada null — Lua ga punya representasi null JSON; null yang di-decode jadi nil (yang ngehapus key dari table).
  • Float vs integer — Lua 5.4 bedain 3 dari 3.0; json.encode jaga bedanya (33, 3.03.0).