Skip to main content

Encode a Lua value to JSON string (json.encode)

Declaration

jsonText, err = json.encode(value)

Parameters

  • value
    Table or String or Number or Boolean or json.null. The Lua value to convert to JSON text.

Returns

  • jsonText
    String or nil. JSON string on success; nil on failure.
  • err
    String or nil. Error message when conversion fails (i.e., when jsonText is nil).

Notes

Converting Lua values to JSON makes it easy to interoperate with other languages.
Note: not every Lua value can be encoded to JSON, e.g., userdata, functions, or tables containing them.
This function can be used in XUI.

Example

local tb = {
["膜"] = "图样图森破桑叹斯乃衣服",
["蛤"] = "比你们高到不知道哪里去了",
moha = {
1,0,0,4,6,9,5,1,0,0,
},
nullvalue = json.null,
}
local jsonstr = json.encode(tb)
sys.alert(jsonstr)
--
local tmp = json.decode(jsonstr)
sys.alert(tmp.moha[5])
sys.alert(tostring(tmp.nullvalue))

Note: Uses sys.alert