將 Lua 值轉成 JSON 字串 (json.encode)
聲明
JSON 文字, 錯誤資訊 = json.encode(值)
參數
- 值
表型 或 文字型 或 數值型 或 布林型 或 json.null,需要轉換成 json 文字的 lua 值
回傳值
- JSON 文字
文字型 或 nil,轉換成功則返回一個 json 字串,否則返回 nil - 錯誤資訊
文字型 或 nil, 轉換失敗 JSON 文字 的值為 nil 的情況下,這個回傳值則是具體的錯誤資訊
說明
將 lua 中的資料值轉成 json 形式可以方便與其它語言交互傳輸
注意 不是任何 lua 值都可以轉成 json。例如:使用者資料或函式及包含使用者資料或函式的表
該函式可在 XUI 中使用
範例
local tb = {
["name"] = "alice",
["message"] = "hello, world",
scores = {
90, 85, 72, 100, 68,
},
nullvalue = json.null,
}
local jsonstr = json.encode(tb)
sys.alert(jsonstr)
--
local tmp = json.decode(jsonstr)
sys.alert(tmp.scores[4])
sys.alert(tostring(tmp.nullvalue))
注:上述代碼中使用了非本章函式 sys.alert